FutureBuilder在显示结果之前显示错误

时间:2020-01-08 08:41:00

标签: firebase flutter

我的futurebuilder在屏幕上显示错误几秒钟,然后显示结果 这是错误日志:

The following NoSuchMethodError was thrown building FutureBuilder<DocumentSnapshot>(dirty, state: _FutureBuilderState<DocumentSnapshot>#fd0c5):
The method '[]' was called on null.
Receiver: null
Tried calling: []("title")

The relevant error-causing widget was: 
  FutureBuilder<DocumentSnapshot> file:///C:/Users/Admin/Desktop/Android/doorstep/lib/domain/repository/booking-repository.dart:7:12
When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
#1      BookingRepository.getTitle.<anonymous closure> (package:doorstep/domain/repository/booking-repository.dart:11:39)
#2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4334:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4223:15)

代码

Widget getTitle(String id) {
  return FutureBuilder(
    future: Firestore.instance.collection('products').document(id).get(),
    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot){
      return ListTile(
        title: Text("${snapshot.data['title'].toString()}"),
      );
    }
  );
}

3 个答案:

答案 0 :(得分:1)

尝试

FutureBuilder<AsyncSnapshot<DocumentSnapshot>>(
        builder: (context, snap) {
          if (snap.connectionState != ConnectionState.done) {
            //print('project snapshot data is: ${snap.data}');
            return Text("loading");
          } else {
            if (snap.hasError) {
              return Text([snap.error.toString()]); 
            }
            else {
              if (snap.hasData) {


                return Text("${snap.data['title'].toString()}");
              } else {
                return Text("No DAta");
              }
            }
          }
        },
        future:
        Firestore.instance.collection('products').document(id).get(),
    );

答案 1 :(得分:1)

根据documentation,应在尝试显示快照之前检查快照是否已包含数据:

builder: (BuildContext context, AsyncSnapshot snapshot) {
  if (snapshot.hasData) {
    // return something
  } else if (snapshot.hasError) {
    // Manage error
  } else {
    // return something for the user to wait
  }
}

答案 2 :(得分:1)

如果不向initialData:的{​​{1}}参数提供任何数据,则将FutureBuilder推入小部件树时将收到null。

也在FutureBuilder的{​​{1}}中

builder:

我希望这会有所帮助,如有任何疑问,请发表评论。