将FutureBuilder与本地JSON一起使用时出错

我不会

我正在尝试加载一些json数据,并已使用afuturebuilder等待数据首先可用,然后显示它。当我尝试将数据加载到时DetailsView,我收到两条日志消息,说没有数据且为null,屏幕错误消失,之后又恢复正常,并且json被记录到控制台。

抛出的异常是The following NoSuchMethodError was thrown building FutureBuilder<String>(dirty, state: _FutureBuilderState<String>#cc31b): The method '[]' was called on null. Receiver: null

样例代码:

body: Container(
      margin: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 15.0),
      child: FutureBuilder(
        future: DefaultAssetBundle.of(context).loadString("assets/my_data.json"), // validly referenced in pubspec and in right folder
        builder: (context, snapshot){
          if(!snapshot.hasData){
            print('no data'); // I understand it will be empty for now
          } else {
            print('hd');
          }
          var data = snapshot.data.toString();
          print(data); // null logged to console, is the future still empty at this point?
          final parsedData = json.decode(data);
          print('pd ${parsedData[1]}'); // this line is where it shows the method [] was called on null
          return data == null || data.isEmpty
              ? LoadingStrengths()
              : MyDataText();
              // : DailyStrengthText(day: widget.day, data: parsedData);
        },
      ),
    ),

问题似乎是:

  1. 我没有正确处理未来
  2. 我无法正确解析json,并在下面附加了它的副本。

样本数据:

[{
    "1": "Each day is an opportunity to start over again"
},
{
    "2": "Every man must at one point be tempted to hoist the black"
},
{
    "3": "Be kind to everyone you meet"
}]

我试图通过使用字符串化的数字作为键来解析它,以访问值。我如何为此或/和在futurebuilder中解析此json制作模型类?谢谢。

-------------------------------编辑------------------ ----------------------这是经过编辑的生成器方法,我可以从中解析并打印出数据:

if(!snapshot.hasData){
            print('no data yet');
            return LoadingStrengths();
          } else {
            print('hd');
            var data = snapshot.data.toString();
            parsedData = json.decode(data);
            print('pd ${parsedData[widget.day - 1]}');
          }
          return Text('${data[widget.day - 1]}'); // it errors out here

当我将值分配给“文本”小部件时,它会显示以下错误消息:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building FutureBuilder<String>(dirty, state: _FutureBuilderState<String>#cc19b):
The method '[]' was called on null.
Receiver: null
Tried calling: [](4)

The relevant error-causing widget was: 
FutureBuilder<String> file:///E:/FlutterProjects/daily_strength/lib/screens/DetailsView.dart:30:18
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1      _DetailsViewState.build.<anonymous closure> 
(package:daily_strength/screens/DetailsView.dart:47:34)
#2      _FutureBuilderState.build 
(package:flutter/src/widgets/async.dart:751:55)
 #3      StatefulElement.build 
(package:flutter/src/widgets/framework.dart:4744:28)
#4      ComponentElement.performRebuild 
(package:flutter/src/widgets/framework.dart:4627:15)

请问这是什么意思?我正在获取数据,但是由于某种原因将其设置为文本小部件不起作用?谢谢。

巴拉吉葫芦

您正在尝试在未加载JSON时对其进行解码。添加了一些注释以进行解释。

if(!snapshot.hasData) {
  // Problem is here, Data has not arrived yet. You are just printing there is
  // no data, but still moving on the next step
  print('no data');
} else {
  print('hd');
}
// data is null right now, toString() just return 'null' in string form
var data = snapshot.data.toString();

// null logged to console, is the future still empty at this point? yes exactly
print(data); 

// 'null' is parsed has null is returned
final parsedData = json.decode(data); 

// parsedData is null, you can't access using [], when it's null, that why exception is thrown
print('pd ${parsedData[1]}'); 

return data == null || data.isEmpty
              ? LoadingStrengths()
              : MyDataText();

解:

if(!snapshot.hasData) {
  return LoadingStrengths(); // return a loader when there is not data
} else {
  // Do stuff when it is loaded;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

将argv与函数一起使用时出错

将statsmodels与pyinstaller一起使用时出错

将fnAddData与数据顺序一起使用时出错

将 ScrollChor 与 NavItem 一起使用时出错

将AutoMapper与异步方法一起使用时出错

将ngMaterial与ngRoute一起使用时出错

将Express会话与Express一起使用时出错

将SharedElementTransition与recyclerView一起使用时出错

将SparkJob与NamedRddSupport一起使用时出错

将cout与指针值一起使用时出错

将 File 与 ImagePicker Flutter 一起使用时出错

将getItem与DynamoDB和节点aws-sdk库一起使用时出错

将Conv2DLayer与lasagne NeuralNet一起使用时出错

将jsonwebtoken与angular-cli应用程序一起使用时出错

将 with 语句与 PostgreSQL 插入查询一起使用时出错

将 wc -c 与文件名一起使用时出错

将布局锚点与 UIStackView 一起使用时出错

将尴尬的数组与索引数组一起使用时出错

尝试将数据绑定提供的上下文变量与BaseObservable一起使用时出错

将预编译的Azure函数与其他方法一起使用时出错

将JQueryUI与TypeScript和DefinitelyTyped定义文件一起使用时出错

NHibernate和C#:将嵌套属性与Criteria一起使用时出错

将GSAP的scrollToPlugin与create-react-app一起使用时出错

将dcast与多个value.var一起使用时出错

将moment.max与mongoDB查询的结果一起使用时出错

将H264_cuvid解码器与ffmpeg一起使用时出错

将bitcore-explorer与bitcore-lib(Bitcore)一起使用时出错

将加载的Keras分类器与自定义指标功能一起使用时出错

将变量与jQuery选择器一起使用时出错