dart Flutter Firestore流构建器返回错误

6jjcrrmo  于 2023-02-06  发布在  Flutter
关注(0)|答案(1)|浏览(113)

我在Firestore中有一个名为Todos的集合,它有3个可能的属性(id,text和checked)。到目前为止,我已经成功地创建并保存了todo。现在我想将它们放在列表视图中,但在热启动时返回错误:

════════ Exception caught by widgets library ═══════════════════════════════════
type 'Null' is not a subtype of type 'String'
The relevant error-causing widget was
StreamBuilder<QuerySnapshot<Object?>>

显示列表视图的代码:

final Stream<QuerySnapshot> _todostream =
      FirebaseFirestore.instance.collection('Todos').snapshots();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Styles.bgColor,
      floatingActionButton: FloatingActionButton(
        onPressed: createNewTask,
        child: const Icon(Icons.add),
      ),
      body: StreamBuilder(
        stream: _todostream,
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) {
            return const Text('Something went wrong');
          }
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const CircularProgressIndicator();
          }
          return ListView(
            children: snapshot.data!.docs.map((DocumentSnapshot document) {
              Map<String, dynamic> data =
                  document.data()! as Map<String, dynamic>;

              return ListTile(title: Text(data['text']));
            }).toList(),
          );
        },
      ),
    );
  }
}

我希望看到一个列表视图与我的收集结果,它包含2个项目。

hfwmuf9z

hfwmuf9z1#

最好接受null并检查它是否包含数据。

body: StreamBuilder(
  stream: _todostream,
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.hasError) {
      return const Text('Something went wrong');
    }
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator();
    }
    if (snapshot.hasData) {
      final data = snapshot.data?.docs.map((e) => e.data()).toList();
      if (data == null) {
        return Text("got null data");
      }
      return ListView.builder(
          itemCount: data.length,
          itemBuilder: (context, index) {
            final map = data[index] as Map?;

            return ListTile(title: Text("${map?['text']}"));
          });
    }

    return Text("NA");
  },
),

相关问题