Home > other >  How to catch exceptions in Flutter streambuilder's stream
How to catch exceptions in Flutter streambuilder's stream

Time:05-17

I want to use try{} catch(){} in my StreamBuilder's Stream, because ${globals.currentUid} is initially set as ''(empty string) and makes exception when the program first runs, but I can't find any way to make try catch in stream.

Below is my 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,
                                  ));
                            }),

This code makes this error : _AssertionError ('package:cloud_firestore/src/firestore.dart': Failed assertion: line 63 pos 7: '!collectionPath.contains('//')': a collection path must not contain "//")

What I want to do is this below,

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,
                                  ));
                                }

and this is grammatically wrong. Is there any solution for this?

CodePudding user response:

The exception in this case is not actually produced by the stream, but rather by the collection method that is called with an invalid argument. You'll probably want to completely avoid creating the StreamBuilder until globals.currentUid has been initialized with a valid value.

You can do so with a simple if statement or with the ternary conditional operator. For example, assuming your StreamBuilder is child to a Container:

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
),
  • Related