0

I'm a flutter null-safe noob. I used the code below, but I am getting this error:

The argument type 'Map<String, dynamic>?' can't be assigned to the parameter type 'Map<String, dynamic>'

This does seem like a null-safe issue but then again it may be that one has to do this getting a stream of documents different in null safety.

class DataService {

final _dataStore = FirebaseFirestore.instance; 

  Stream <List<Shop>> listAllShops() {    
    return _dataStore.collection('shops')
      .snapshots()
      .map((snapshot) => snapshot.docs
        .map((document) => Shop.fromJson(document.data())) <<< error comes here
        .toList());
  }
}

I have tried putting a ? in various places but nothing worked.

Chris Laurie
  • 33
  • 1
  • 5

2 Answers2

1

Though you don't show it, the Shop.fromJson constructor likely takes a Map<String, dynamic> type. A non-nullable type. The data function referenced in document.data() returns a nullable type. You just need to promote the nullable type to a non-nullable type.

This can be easily done with the bang operator ! if you're sure the data will not be null:

Stream <List<Shop>> listAllShops() {    
    return _dataStore.collection('shops')
      .snapshots()
      .map((snapshot) => snapshot.docs
        .map((document) => Shop.fromJson(document.data()!))
        .toList());
  }
Christopher Moore
  • 15,626
  • 10
  • 42
  • 52
0

In the following code:

document.data()

document.data() can be null which is why you see an error. If you're sure that it will never be null, just use

document.data()!
iDecode
  • 22,623
  • 19
  • 99
  • 186