Reputation: 1
StreamBuilder<QuerySnapshot>(
stream: _fire.collection('messages').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final messages = snapshot.data!.docs;
List<Text> messageWidgets = [];
for (var message in messages) {
final messageText = message.get('text');
final messageSender = message.get('sender');
final messageWidget =
Text('$messageText from $messageSender');
messageWidgets.add(messageWidget);
}
return Column(
children: messageWidgets,
);
}
},
),
builder:(context, snapshot){ starting bracket show this error: The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type Try adding either a return or a throw statement at the end.
Upvotes: 0
Views: 79
Reputation: 172
The idea is to make sure the body of your StreamBuilder
returns a Widget
that is non-nullable, and because your return statement is nested within your if statement makes it conditional so assuming the if statement returns false or the data you are requesting isn't available the body of your StreamBuilder
would return null
and that's why you have the above error.
Here is a piece of you could try:
class Sample extends StatelessWidget {
const Sample({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: _fire.collection('messages').snapshots(),
builder: (context, snapshot) {
if (snapshot.hasData) {
final messages = snapshot.data!.docs;
List<Text> messageWidgets = [];
for (var message in messages) {
final messageText = message.get('text');
final messageSender = message.get('sender');
final messageWidget =
Text('$messageText from $messageSender');
messageWidgets.add(messageWidget);
}
}
return Column(
children: messageWidgets,
);
},
);
}
}
additionally you want to check the ConnectionState
of the resulting snapshot to help create a meaningful flow so you can have to Loading Indicator of your choice show up while your data is being loaded and neatly show the requested data when it becomes available
Upvotes: 0