如何在 Flutter streambuilder 的流中捕获异常

How to catch exceptions in Flutter streambuilder's stream

我想在我的 StreamBuilder 的 Stream 中使用 try{} catch(){},因为 ${globals.currentUid} 最初设置为 ''(空字符串)并在程序首次运行时抛出异常, 但我找不到任何方法让 try catch 进入流。

下面是我的streamBuilder

StreamBuilder(
                            stream: FirebaseFirestore.instance
                                .collection(
                                    'user/${globals.currentUid}/friends')
                                .snapshots(),
                            builder: (BuildContext context,
                                AsyncSnapshot snapshot) {
                              if (snapshot.connectionState ==
                                  ConnectionState.waiting) {
                                return Center(
                                  child: CircularProgressIndicator(),
                                );
                              }
                              if (snapshot.hasError) {
                                return Text(
                                  'Error: ${snapshot.error}',
                                );
                              }

                              final docs = snapshot.data!.docs;
                              return Text(
                                  docs.length.toString(),
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                  ));
                            }),

此代码会导致此错误: _AssertionError ('package:cloud_firestore/src/firestore.dart': 断言失败: 第 63 行 pos 7: '!collectionPath.contains('//')': 集合路径不能包含“//”)

我要做的就是下面这个,

try{
                        StreamBuilder(
                            stream: FirebaseFirestore.instance
                                .collection(
                                    'user/${globals.currentUid}/friends')
                                .snapshots(),
                            builder: (BuildContext context,
                                AsyncSnapshot snapshot) {
                              if (snapshot.connectionState ==
                                  ConnectionState.waiting) {
                                return Center(
                                  child: CircularProgressIndicator(),
                                );
                              }
                              if (snapshot.hasError) {
                                return Text(
                                  'Error: ${snapshot.error}',
                                );
                              }

                              final docs = snapshot.data!.docs;
                              return Text(docs.length.toString(),
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                  ));
                            })
                            } on _AssertionError catch(e){
                                  return Text('0',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                  ));
                                }

这在语法上是错误的。有解决办法吗?

这种情况下的异常实际上不是由流产生的,而是由使用无效参数调用的 collection 方法产生的。在使用有效值初始化 globals.currentUid 之前,您可能希望完全避免创建 StreamBuilder

您可以使用简单的 if 语句或三元条件运算符来实现。例如,假设您的 StreamBuilder 是容器的子级:

Container(
    child: globals.currentUid != '' ?
        StreamBuilder( // This will be built only if currentUid is not empty
            stream: FirebaseFirestore.instance
                    .collection(
                        'user/${globals.currentUid}/friends')
                    .snapshots(),
            builder: (
                BuildContext context,
                AsyncSnapshot snapshot,
            ) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                    return Center(
                        child: CircularProgressIndicator(),
                    );
                }

                if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                }

                final docs = snapshot.data!.docs;
                return Text(
                    docs.length.toString(),
                    style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                    ),
                );
            },
        )
        : Container(), // An empty container will be shown if currentUid is empty
),