flutter 发生异常,_CastError(对空值使用了空检查运算符)

l5tcr1uw  于 2023-01-06  发布在  Flutter
关注(0)|答案(2)|浏览(159)

这是我的密码

@override
Widget build(BuildContext context) {
 return Scaffold(
  body:StreamBuilder(
    stream:FirebaseFirestore.instance
           .collection('chats/r7T0B5xmCSgKQFLl2uNj/messages')
           .snapshots(),
           builder:(context,streamSnapshot) {
            return ListView.builder(
             itemCount: streamSnapshot.data!.docs.length,
              itemBuilder:(ctx, index) =>
            Container(
              padding: const EdgeInsets.all(8),
               child: const Text("This Work!"),
             ),);
           } ,),
        floatingActionButton: FloatingActionButton(
          onPressed: (){},
       ),
   );
  }
}

itemCount: streamSnapshot.data!.docs.length上使用空检查运算符时,此行出现异常,未进行空检查时出现错误

mklgxw1f

mklgxw1f1#

获取数据需要一些时间,因此最初它将为null。此问题是由于使用bang !强制not null引起的。
您可以执行itemCount: streamSnapshot.data?.docs.length,
但更好的情况是,

body: StreamBuilder(
  stream: FirebaseFirestore.instance
      .collection('chats/r7T0B5xmCSgKQFLl2uNj/messages')
      .snapshots(),
  builder: (context, streamSnapshot) {
    if (streamSnapshot.hasError) {
      return Text("Error");
    }
    if (streamSnapshot.hasData) {
      return ListView.builder(
        itemCount: streamSnapshot.data?.docs.length,
        itemBuilder: (ctx, index) => Container(
          padding: const EdgeInsets.all(8),
          child: const Text("This Work!"),
        ),
      );
    }

    return CircularProgressIndicator();
  },
),

查找有关使用StreamBuilder的详细信息

lyr7nygr

lyr7nygr2#

检查空值以获取数据长度使用空值安全:

StreamBuilder(
        stream: FirebaseFirestore.instance
            .collection('chats/r7T0B5xmCSgKQFLl2uNj/messages')
            .snapshots(),
        builder: (context, streamSnapshot) {
          if (streamSnapshot.hasData) {
            return ListView.builder(
              itemCount: streamSnapshot.data?.docs.length ?? 0,
              itemBuilder: (ctx, index) => Container(
                padding: const EdgeInsets.all(8),
                child: const Text("This Work!"),
              ),
            );
          } else {
            return Container();
          }
        },
      ),

相关问题