简体   繁体   English

Flutter Future:构建函数返回null

[英]Flutter Future:A build function returned null

I want to retrieve data from firebase to future builder.I use this function for that. 我想从Firebase检索数据到将来的生成器。为此我使用了此功能。

Future getAllData() async {
  ReseviorDataModel resModel;
  DatabaseReference ref = FirebaseDatabase.instance.reference();
  DataSnapshot childed =await 
  ref.child("Reservoir/${widget.placeName}").once();
  Map<dynamic, dynamic> values;
  values = childed.value;
  resModel = ReseviorDataModel.customConstrcutor(values["sensor1"], 
  values["sensor2"], values["sensor3"]);
  return resModel;
}

I invoke this function inside my future builder. 我在未来的构建器中调用此函数。

  child: FutureBuilder(
         future: getAllData(),
         builder: (context, snapshot) {
         Center(child: Text(snapshot.data));
  }

but it keeps throwing this "A build function returned null." 但它总是抛出“构建函数返回null”的错误。 error .i cant figure out what is the problem here 错误。我无法弄清楚问题出在哪里

To clear things up here, your builder always has to return a widget to display. 要在此处清除内容,您的构建器始终必须返回一个小部件以进行显示。 You can never return null, as the error message describes. 如错误消息所述,您永远不能返回null。

The problem in this case was that the OP didn't return anything from the builder, so just adding a return worked out fine. 在这种情况下的问题是,OP没有从构建器返回任何东西,因此仅添加返回值就可以了。

Some things to keep in mind when using FutureBuilder. 使用FutureBuilder时要记住一些注意事项。 Always check the snapshot.hasData property and return a UI accordingly. 请始终检查snapshot.hasData属性并相应地返回一个UI。 This will prevent cases where the snapshot.data is null causing a new error to be thrown in your Widget taking in the null. 这将防止快照.data为null的情况导致在Widget中使用null引发新错误。

Example: 例:

child: FutureBuilder(
     future: getAllData(),
     builder: (context, snapshot) {
     if(!snapshot.hasData) {
         // show loading while waiting for real data
        return CircularProgressIndicator();
     }

     return Center(child: Text(snapshot.data));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM