Home > database >  Flutter - A non-null value must be returned since the return type 'Widget' doesn't al
Flutter - A non-null value must be returned since the return type 'Widget' doesn't al

Time:05-21

I tried to run this code but it gives me the error provided in the title, also it says (The body might complete normally, causing 'null' to be returned, but the return type, 'Widget', is a potentially non-nullable type.), any help to solve this issue would be appreciated!

    Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: FirebaseFirestore.instance.collection("chats").snapshots(),
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
        if(snapshot.hasError) {
          return Center (
            child: Text("There is a problem"),
          );
        }

        if(snapshot.connectionState == ConnectionState.waiting) {
          return Center (
            child: Text("Loading"),
          );
        }

        if(snapshot.hasData) {
          return CustomScrollView(
            slivers: [
              CupertinoSliverNavigationBar(
                largeTitle: Text("Chats"),
              ),

              SliverList(
                delegate: (
                    SliverChildListDelegate(
                      snapshot.data!.docs.map((DocumentSnapshot document) {
                        Map<String, dynamic> data = document.data()!as Map<String, dynamic>;
                        return CupertinoListTile(title: Text(data['title']),
                        );
                      }).toList())))
            ],
          );
      }
  });
  }

CodePudding user response:

You need to return a widget after if(snapshot.hasData) .I guess you can simply remove if(snapshot.hasData) and your code would be fine. But for assurance, you can return an error widget after that .

CodePudding user response:

From the builder you are retuning widget with checking conditions, and it is good practice. You can return a default widget at the end. Also, you can use else state. The error show up by editor because it thinks we might face other state and that might not fit with theses if. It expects a default return widget that be with or without else condition.

builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot){
 
if(...)

if(...)


else return Text(...); // with or without else condition it will retrun by default. 
}
  • Related