How to fix – The body might complete normally causing null to be returned –FLUTTER

Issue

I am using a stream builder to fetch some data from Firebase but it’s giving me an error

"The body might complete normally causing ‘null’ to be returned"

although I have provided a return statement where I am returning the ‘data table’ widget
here is my code

StreamBuilder<QuerySnapshot?>(
              stream: _firestore.collection('cashOut').snapshots(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  List<DataCell> displayedDataCell = [];

                  for (var item in snapshot.data!.docs) {
                    displayedDataCell.add(
                      DataCell(
                        Text(
                          item['amount'].toString(),
                        ),
                      ),
                    );
                  }
                  return DataTable(
                    columns: const <DataColumn>[
                      DataColumn(
                        label: Text(
                          'Date',
                        ),
                      ),
                      DataColumn(
                        label: Text(
                          'Amount',
                        ),
                      ),
                      DataColumn(
                        label: Text(
                          'Optional Detail',
                        ),
                      ),
                    ],
                    rows: <DataRow>[
                      DataRow(cells: displayedDataCell),
                    ],
                  );
                }
              },
            ),

Solution

the builder function requires a widget to return. In your case, you are returning the widget but it is in if condition. This means that if your if condition didn’t satisfy, your builder will return null which is not acceptable.

Now, as per other answers, you can handle other states and return things. But if you don’t want to handle the other states and you also don’t want to show a loader, at the end of your if block, just add return Container(); or return SizedBox();

So, in this way, you won’t be showing anything on the screen if the if condition didn’t satisfy.

Answered By – Abhishek Doshi

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *