Flutter - json_serializable fromJson: The method '[]' was called on null

2,814

Check for @JsonSerializable(nullable: false) in your class members (start with ZutatenModel and RecipeModel).

If you expect them to be null sometimes, do not mark nullable: false while annotating their model class.

If it is the case, change it to @JsonSerializable(nullable: true). It is set true by default btw.

This exception usually occurs when some class attributes are provided null but (nullable: false) suggests to JsonSerializer that these will not be null.

Share:
2,814
Jaymin
Author by

Jaymin

नमस्ते I am Jaymin Nayak from India. But everyone calls me JIMMY! Jimmy the iron-born – First of his name, a passionate about learning new technologies, Self-motivating, king of sarcasm, die-hard IronMan fan, and above all – Mobile Application Developer. Currently Working On: Kotlin Xamarin Paython Machine Learning Platforms I've worked on: Android Native Application Development Xamarin Application Development Spy on me: Twitter, Quora, LinkedIn, Medium

Updated on December 08, 2022

Comments

  • Jaymin
    Jaymin over 1 year

    In my app, I am exporting data to JSON. But when I am trying to import the JSON file it throws an error that looks like the following:

    E/flutter: [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception: NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5) #1 _$RecipesModelFromJson (file:///home/stube/IdeaProjects/Flutter_Recipe/lib/JSON/recipes.g.dart:11:11) #2 new RecipesModel.fromJson (package:Time2Eat/JSON/recipes.dart:20:63) #3 _$RecipesModelFromJson (file:///home/stube/IdeaProjects/Flutter_Recipe/lib/JSON/recipes.g.dart:32:22) #4 new RecipesModel.fromJson (package:Time2Eat/JSON/recipes.dart:20:63) #5 RecipebookState.createRecipeJson (package:Time2Eat/recipe/recipebook.dart:111:32) #6 RecipebookState.getPath (package:Time2Eat/recipe/recipebook.dart:123:9) #7 RecipebookState.build. (package:Time2Eat/recipe/recipebook.dart:185:19) #8 AnimatedChild._performAction (package:flutter_speed_dial/src/animated_child.dart:60:24) #9 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14) #10 _InkResponseState.build. (package:flutter/src/material/ink_well.dart:562:30) #11 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24) #12 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9) #13 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7) #14 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9) #15 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12) #16 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11) #17 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19) #18 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22) #19 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7) #20 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7) #21 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7) #22 _invoke1 (dart:ui/hooks.dart:173:13) #23 _dispatchPointerDataPacket (dart:ui/hooks.dart:127:5)

    recipes.g.dart, that was generated by json_serializable:

    // **************************************************************************
    // JsonSerializableGenerator
    // **************************************************************************
    
    RecipesModel _$RecipesModelFromJson(Map<String, dynamic> json) {
      return RecipesModel(
          json['name'] as String,
          json['image'] as String,
          json['description'] as String,
          json['favorite'] as int,
          json['timestamp'] as String,
          json['preperation'] as String,
          json['creation'] as String,
          json['resting'] as String,
          json['people'] as String,
          json['backgroundColor'] as String,
          (json['zutaten'] as List)
              ?.map((e) => e == null
                  ? null
                  : ZutatenModel.fromJson(e as Map<String, dynamic>))
              ?.toList(),
          (json['zubereitung'] as List)
              ?.map((e) => e == null
                  ? null
                  : ZubereitungModel.fromJson(e as Map<String, dynamic>))
              ?.toList())
        ..recipeModel =
            RecipesModel.fromJson(json['recipeModel'] as Map<String, dynamic>);
    }
    
    Map<String, dynamic> _$RecipesModelToJson(RecipesModel instance) =>
        <String, dynamic>{
          'name': instance.name,
          'image': instance.image,
          'description': instance.description,
          'favorite': instance.favorite,
          'timestamp': instance.timestamp,
          'preperation': instance.preperation,
          'creation': instance.creation,
          'resting': instance.resting,
          'people': instance.people,
          'backgroundColor': instance.backgroundColor,
          'zutaten': instance.zutaten,
          'zubereitung': instance.zubereitung,
          'recipeModel': instance.recipeModel
        };
    
    ZutatenModel _$ZutatenModelFromJson(Map<String, dynamic> json) {
      return ZutatenModel(
          json['zutat'] as String,
          json['number'] as String,
          json['measure'] as String
      );
    }
    
    Map<String, dynamic> _$ZutatenModelToJson(ZutatenModel instance) =>
        <String, dynamic>{
          'zutat': instance.zutat,
          'number': instance.number,
          'measure': instance.measure
        };
    
    ZubereitungModel _$ZubereitungModelFromJson(Map<String, dynamic> json) {
      return ZubereitungModel(json['number'] as String, json['steps'] as String);
    }
    
    Map<String, dynamic> _$ZubereitungModelToJson(ZubereitungModel instance) =>
        <String, dynamic>{'number': instance.number, 'steps': instance.steps};
    

    I am calling the method RecipesModel.fromJson() inside a function, that should be able to save this data inside the database. The function looks like this:

    createJson() async{
          FlutterDocumentPickerParams params = FlutterDocumentPickerParams(
              allowedFileExtensions: ['json'],
              invalidFileNameSymbols: ['/']
          );
          final path = await FlutterDocumentPicker.openDocument(params: params);
          File file = new File(path);
          createRecipeJson(file);
          Map<String,dynamic> jSON = json.decode(path.readAsStringSync());
          var model = RecipesModel.fromJson(jSON);
          showBottomSnack("Name: ${model.name}", ToastGravity.BOTTOM);
        }
    

    I hope somebody could help me out and solve my problem. That would be awesome.

  • Maoration
    Maoration over 3 years
    Thanks for your answer. I was twisting around with this problem until I figured out from what your wrote that (nullable: false) on the model class somehow dictates -not null- for all class properties. Had to remove that, and annotate each property individually, and problem solved.