0

I have recently upgraded my flutter to the latest version and I am getting all the null safety errors.

StreamBuilder(
stream: FirebaseFirestore.instance
  .collection('restaurants')
  .doc(partnerId)
  .snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
  return Center(
    child: CircularProgressIndicator(),
  );
}
final restaurant = snapshot.data;
startTime = restaurant['startTime'].toDate();
endTime = restaurant['endTime'].toDate();

I am getting the following error when I assign restaurant[''] to any variable.

The method '[]' can't be unconditionally invoked because the receiver can be 'null'.

If I do this - restaurant!['endTime'].toDate();, new error comes

The operator '[]' isn't defined for the type 'Object'. Try defining the operator '[]'.

RobC
  • 22,977
  • 20
  • 73
  • 80
mustafa zaki
  • 367
  • 1
  • 6
  • 20

2 Answers2

1

try casting the snapshot.data to whatever your stream returns.

example: if your stream returns a Map, here is your code:

StreamBuilder(
stream: FirebaseFirestore.instance
  .collection('restaurants')
  .doc(partnerId)
  .snapshots(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
  return Center(
    child: CircularProgressIndicator(),
  );
}

// dont forget to assume that your stream may
// have an error, or dont return data.
if(!snapshot.hasData) return Container();

final restaurant = snapshot.data as Map;
startTime = restaurant['startTime'].toDate();
endTime = restaurant['endTime'].toDate();
Adnan
  • 906
  • 13
  • 30
  • That worked, thanks! Also, I am getting a similar error on snapshot.data.docs - final documents = snapshot.data!.docs; – mustafa zaki Jun 10 '21 at 10:48
  • well, you can use the same method, `final documents = snapshot.data!.docs as Map;`, but reaplace `Map` with whatever the docs' datatype is – Adnan Jun 11 '21 at 10:22
0

snapshot.data is an AsyncSnapshot. You have to do the following: Map<String, dynamic> restaurant = snapshot.data.data() if you're getting a single document.

krumpli
  • 723
  • 3
  • 15