Flutter-来自Json的json_serializable:方法'[]'在null

时间:2018-12-18 12:33:47

标签: android ios json dart flutter

在我的应用中,我正在将数据导出到JSON。但是,当我尝试导入JSON文件时,它将引发类似于以下内容的错误:

  

E / flutter:[错误:flutter / shell / common / shell.cc(184)] Dart错误:未处理的异常:           NoSuchMethodError:方法'[]'在null上调用。           接收者:null           尝试致电:           #0 Object.noSuchMethod(dart:core / runtime / libobject_patch.dart:50:5)           #1 _ $ RecipesModelFromJson(文件:///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(文件:///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。 (包:Time2Eat / recipe / recipebook.dart:185:19)           #8 AnimatedChild._performAction(package:flutter_speed_dial / src / animated_child.dart:60:24)           #9 _InkResponseState._handleTap(包:flutter / src / material / ink_well.dart:507:14)           #10 _InkResponseState.build。 (包:flutter / src / material / ink_well.dart:562:30)           #11 GestureRecognizer.invokeCallback(package:flutter / src / gestures / recognizer.dart:102:24)           #12 TapGestureRecognizer._checkUp(包:flutter / src / gestures / tap.dart:242:9)           #13 TapGestureRecognizer.handlePrimaryPointer(软件包:flutter / src / gestures / tap.dart:175:7)           #14 PrimaryPointerGestureRecognizer.handleEvent(package:flutter / src / gestures / recognizer.dart:315:9)           #15 PointerRouter._dispatch(软件包:flutter / src / gestures / pointer_router.dart:73:12)           #16 PointerRouter.route(软件包: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(包:flutter / src / gestures / binding.dart:85:7)           #22 _invoke1(dart:ui / hooks.dart:173:13)           #23 _dispatchPointerDataPacket(dart:ui / hooks.dart:127:5)

由json_serializable生成的

recipes.g.dart

// **************************************************************************
// 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};

我正在函数内部调用RecipesModel.fromJson()方法,该函数应该能够将此数据保存在数据库中。该函数如下所示:

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);
    }

我希望有人能帮助我并解决我的问题。太棒了。

1 个答案:

答案 0 :(得分:0)

检查类成员中的@JsonSerializable(nullable: false)(从ZutatenModel和RecipeModel开始)。

如果您期望它们有时为null,则在注释其模型类时不要标记nullable: false

在这种情况下,请将其更改为@JsonSerializable(nullable: true)。顺便说一句,默认设置为true。

当提供某些类属性null时,通常会发生此异常,但是(nullable: false)向JsonSerializer建议这些属性不会为空。