flutter JSON decoding Unhandled Exception: type 'Null' is not a subtype of type 'String'
902
I am sure you are receiving the null value from the json.
so add this null safety operator on each statement
where you are assigning the values e.g.
cm.name = jsonData['drinks'][0]['strDrink'] ?? "";
Author by
Mimir
Updated on December 30, 2022Comments
-
Mimir over 1 year
I followed a video tutorial to make an app that shows different cocktails and how to make them, but in the end, I faced an error that I don't know how to solve. I looked up the error but I couldn't find out what is causing it. This is the error that I get;
> Unhandled Exception: type 'Null' is not a subtype of type 'String'
I get this error on my searchpage.dart and this is the code:
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:http/http.dart'; import 'package:mimir_cocktails/constants.dart'; import 'package:mimir_cocktails/pages/cocktail_page.dart'; import 'package:mimir_cocktails/services/cocktail_manager.dart'; import 'package:mimir_cocktails/services/ingredients.dart'; class SearchPage extends StatefulWidget { // SearchPage({Key? key}) : super(key: key); @override _SearchPageState createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { String cocktailName = 'margarita'; var _deviceWidth; var _deviceHeight; @override Widget build(BuildContext context) { _deviceWidth = MediaQuery.of(context).size.width; _deviceHeight = MediaQuery.of(context).size.height; return Scaffold( body: SafeArea( child: Center( child: Padding( padding: EdgeInsets.all(12.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: [ // The Logo Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(100), ), height: _deviceHeight * 0.25, width: _deviceWidth * 0.5, child: Image(image: AssetImage('assets/cocktails_logo.png')), ), // Title Text( 'Mimir Cocktails', style: GoogleFonts.raleway(fontSize: 35), ), SizedBox(height: 32), // Textfield TextField( onChanged: (value) { value = cocktailName; }, decoration: InputDecoration( contentPadding: EdgeInsets.all(15), hintText: 'Search for a Cocktail', border: kBorderStyle, focusedBorder: kFocusedBorderStyle, ), ), SizedBox(height: 20), // SearchBTN ElevatedButton( onPressed: () async { // ignore: unnecessary_null_comparison if (cocktailName == null) return; cocktailName.toLowerCase().replaceAll(' ', '_'); CocktailManager cm = CocktailManager(); var network = await get(Uri.parse(kMainURL + cocktailName)); var jsonData = jsonDecode(network.body); cm.name = jsonData['drinks'][0]['strDrink']; cm.category = jsonData['drinks'][0]['strCategory']; cm.alcoholic = jsonData['drinks'][0]['strAlcoholic']; cm.glassType = jsonData['drinks'][0]['strGlass']; cm.imgURL = jsonData['drinks'][0]['strDrinkThumb']; cm.instructions = jsonData['drinks'][0]['strInstructions']; String strIngredientName, strIngredientMesure; List<Ingredient> ingredientList = []; for (var ings = 1; ings < 16; ings++) { strIngredientName = 'strIngredientName' + ings.toString(); strIngredientMesure = 'strIngredientMesure' + ings.toString(); ingredientList.add( Ingredient( name: jsonData['drinks'][0][strIngredientName], mesure: jsonData['drinks'][0][strIngredientMesure], ), ); ingredientList.removeWhere((element) => // ignore: unnecessary_null_comparison element.name == null && element.mesure == null); ingredientList.forEach((element) { // ignore: unnecessary_null_comparison if (element.mesure == null) { element.mesure = 'as you wish'; } }); } cm.ingredients = ingredientList; Navigator.push( context, MaterialPageRoute(builder: (context) { return CocktailPage( name: cm.name, category: cm.category, alcoholic: cm.alcoholic, glassType: cm.glassType, imgURL: cm.imgURL, instructions: cm.instructions, ingredients: cm.ingredients); }), ); }, child: Text( 'Search', style: GoogleFonts.ubuntu(fontSize: 25), ), style: ElevatedButton.styleFrom( primary: kAccentColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25)), minimumSize: Size(_deviceWidth * 0.65, 48), ), ), SizedBox(height: 15), // RandomBTN ElevatedButton( onPressed: () async { CocktailManager cm = CocktailManager(); var network = await get(Uri.parse(kMainURL + cocktailName)); var jsonData = jsonDecode(network.body); cm.name = jsonData['drinks'][0]['strDrink']; cm.category = jsonData['drinks'][0]['strCategory']; cm.alcoholic = jsonData['drinks'][0]['strAlcoholic']; cm.glassType = jsonData['drinks'][0]['strGlass']; cm.imgURL = jsonData['drinks'][0]['strDrinkThumb']; cm.instructions = jsonData['drinks'][0]['strInstructions']; // ignore: unused_local_variable String? strIngredientName, strIngredientMesure; List<Ingredient> ingredientList = []; for (var ings = 1; ings < 16; ings++) { strIngredientName = 'strIngredientName' + ings.toString(); strIngredientMesure = 'strIngredientMesure' + ings.toString(); ingredientList.add( Ingredient( name: jsonData['drinks'][0][strIngredientName], mesure: jsonData['drinks'][0][strIngredientMesure], ), ); ingredientList.removeWhere((element) => // ignore: unnecessary_null_comparison element.name == null && element.mesure == null); ingredientList.forEach((element) { // ignore: unnecessary_null_comparison if (element.mesure == null) { element.mesure = 'as you wish'; } }); } cm.ingredients = ingredientList; Navigator.push( context, MaterialPageRoute(builder: (context) { return CocktailPage( name: cm.name, category: cm.category, alcoholic: cm.alcoholic, glassType: cm.glassType, imgURL: cm.imgURL, instructions: cm.instructions, ingredients: cm.ingredients); }), ); }, child: Text( 'Feeling Locky', style: GoogleFonts.ubuntu(fontSize: 25), ), style: ElevatedButton.styleFrom( primary: kAccentColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25)), minimumSize: Size(_deviceWidth * 0.65, 48), ), ), ], ), ), ), ), ); } }
and this is where I get my error
ingredientList.add( Ingredient( name: jsonData['drinks'][0][strIngredientName], mesure: jsonData['drinks'][0][strIngredientMesure], ),
and this is my coctail_manager.dart
import 'package:mimir_cocktails/services/ingredients.dart'; class CocktailManager { String? name; String? category; String? alcoholic; String? glassType; String? imgURL; String? instructions; List<Ingredient>? ingredients; CocktailManager({ this.name, this.category, this.alcoholic, this.glassType, this.imgURL, this.instructions, this.ingredients, }); }
would you please have a look and let me know what the problem is this is the Github repository if you want to check the whole app.