【问题标题】:"Read Data from Firebase", not working after update 2.8.1“从 Firebase 读取数据”,更新 2.8.1 后无法正常工作
【发布时间】:2022-01-22 11:30:33
【问题描述】:

解决方案

返回前添加代码

 if (!snapshot.hasData) {
          return const Scaffold(
            body: Center(
                child: CircularProgressIndicator(
              color: Colors.red,
            )),
          );
        }

重要! - if (!snapshot.hasData)


我尝试显示来自 FireBase 的数据,我在 Firestore 上有数据库。

我今天更新了 Flutter (2.8.0 -> 2.8.1) ,代码在更新之前工作

我的代码

import 'package:cloud_firestore/cloud_firestore.dart';

class FireService extends StatefulWidget {

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

class _FireServiceState extends State<FireService> {
  final Stream<QuerySnapshot> _usersStream = FirebaseFirestore.instance
      .collection('chats/uHdJ4WvHjvphsBUpb9yk/visits')
      .snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Visits'),
      ),
      body: StreamBuilder(
          stream: _usersStream,
          builder:
              (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            return ListView(
              children: snapshot.data!.docs.map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return Card(
                  child: ListTile(
                    title: Text(
                      data['company'],
                      style: TextStyle(fontSize: 19, color: Colors.black),
                    ),
                    subtitle: Text(
                      data['number_visit'].toString(),
                    ),
                    leading: Icon(
                      Icons.local_offer,
                      size: 40,
                      color: Colors.red,
                    ),
                  ),
                );
              }).toList(),
            );
          }),
    );
  }
}

启动后出现错误

enter image description here

请编写一个新代码,以便我理解错误。谢谢

UPD 1.

我尝试了一个选项

children: snapshot.data?.docs.map((DocumentSnapshot document) {

一个新的错误 - 整个代码块用红线

enter image description here

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    您的行 snapshot.data!.docs.map 应该使用无效合并而不是 !。

    该行应该是:

    snapshot.data?.docs.map
    

    如果数据为空,data?. 将优雅地中断

    【讨论】:

    • 我尝试了一个选项,一个新的错误——整个代码块有一条红线
    猜你喜欢
    • 2019-08-10
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多