从 Firebase 检索数据时出现短错误

Short error when data is retrieved from Firebase

我正在从 Firebase 检索文档并尝试在我的应用程序中显示此数据。 用户单击了一个项目并被转发到此处的此页面。同时转发选中商品的信息,代码如下:

Navigator.of(context).push(
            MaterialPageRoute(
            builder: (context) => SearchResult(item.abc)));

以下代码的结果是正确的,并且显示了正确的名称。但是加载时会短暂出现此错误:

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building SearchResult(dirty, state: 
_SearchResultState#9a2f6):
The method '[]' was called on null.
Receiver: null
Tried calling: []("Name")

片刻之后,该名称显示在我的应用程序中。我认为这是从 Firebase 加载数据的问题。我该如何解决这个问题? 这是我的代码:

class SearchResult extends StatefulWidget {
  final String data;
  SearchResult(this.data);

  @override
  _SearchResultState createState() => _SearchResultState();
}

class _SearchResultState extends State<SearchResult>  {
  dynamic data_snap;

Future<dynamic> getData() async{
print(widget.data);
final DocumentReference document = Firestore.instance.collection("Players").document(widget.data);
await document.get().then<dynamic>(( DocumentSnapshot snapshot) async{
  setState(() {
    data_snap =snapshot.data;
  });
});
}
  
@override
  void initState() {
  super.initState();
  getData();
}

  @override
  Widget build(BuildContext context) {

return Scaffold(
  appBar: AppBar(
    title: const Text('Player'),
  ),
  body: Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.black)
              ),
              child: ListTile(
                title: Text(data_snap['Name']),
              ),
            )
          ]
      )
  ),
);
 }
}

这可能会发生,因为当构建方法运行时,应用程序可能仍在获取数据,您应该控制它并在这种情况下添加进度指示器

尝试这样的事情:

class _SearchResultState extends State<SearchResult>  {
dynamic data_snap;
bool _loading = false;

Future<dynamic> getData() async{
print(widget.data);
    final DocumentReference document = 
Firestore.instance.collection("Players").document(widget.data);
       _loading = true;
    await document.get().then<dynamic>(( DocumentSnapshot snapshot) async{
      setState(() {
        data_snap =snapshot.data;
        _loading = false;
      });
    });
    }

然后在您的构建方法中执行以下操作:

  child: _loading ? CircularProgressIndicator() : 
         ListTile(
            title: Text(data_snap['Name']),
          ),