Flutter - json_serializable fromJson:在 null 上调用了方法“[]”

Posted

技术标签:

【中文标题】Flutter - json_serializable fromJson:在 null 上调用了方法“[]”【英文标题】:Flutter - json_serializable fromJson: The method '[]' was called on null 【发布时间】:2019-05-18 21:01:50 【问题描述】:

在我的应用程序中,我将数据导出为 JSON。但是当我尝试导入 JSON 文件时,它会引发如下所示的错误:

E/flutter: [ERROR:flutter/shell/common/shell.cc(184)] Dart 错误:未处理的异常: NoSuchMethodError:在 null 上调用了方法“[]”。 接收方:空 尝试调用: #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 新RecipesModel.fromJson(包:Time2Eat/JSON/recipes.dart:20:63) #3 _$RecipesModelFromJson (file:///home/stube/IdeaProjects/Flutter_Recipe/lib/JSON/recipes.g.dart:32:22) #4 新RecipesModel.fromJson(包:Time2Eat/JSON/recipes.dart:20:63) #5 RecipebookState.createRecipeJson (包:Time2Eat/recipe/recipebook.dart:111:32) #6 RecipebookState.getPath (package:Time2Eat/recipe/recipebook.dart:123:9) #7 食谱书状态.build。 (包: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。 (包: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(包: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,由 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;

我在函数内部调用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】:

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

如果您希望它们有时是null,请不要在注释它们的模型类时标记nullable: false

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

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

【讨论】:

感谢您的回答。我一直在纠结这个问题,直到我从你写的模型类上发现(可为空:false)以某种方式规定所有类属性 - 不为空 - 。必须删除它,并单独注释每个属性,问题就解决了。

以上是关于Flutter - json_serializable fromJson:在 null 上调用了方法“[]”的主要内容,如果未能解决你的问题,请参考以下文章

[Flutter] flutter项目一直卡在 Running Gradle task 'assembleDebug'...

flutter 日志输出,Flutter打印日志,flutter log,flutter 真机日志

Flutter开发 Flutter 包和插件 ( Flutter 包和插件简介 | 创建 Flutter 插件 | 创建 Dart 包 )

flutter与原生混编(iOS)

Flutter-布局

如何解决flutter gradle build error?C:\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 991