-1

I get the error:

'Null' is not a subtype of type 'Map<String, dynamic>' in type cast

 @override
  void initState() {
    FirebaseFirestore.instance.collection('user').doc(widget.id);
    AsyncSnapshot<DocumentSnapshot>? snapshot;
    Map<String, dynamic> data = snapshot?.data!.data() as Map<String, dynamic>;
    
    super.initState();
  }
lepsch
  • 8,927
  • 5
  • 24
  • 44
husam
  • 33
  • 1
  • 6

1 Answers1

1

snapshot?.data!.data() evaluates to null because snapshot is null. And trying to cast it to a map with as Map<String, dynamic> throws this error.

To fix it use a ternary operator like that (assuming data should not be null):

Map<String, dynamic> data = snapshot?.data?.data() != null
  ? snapshot?.data!.data()! as Map<String, dynamic>
  : <String, dynamic>{};
lepsch
  • 8,927
  • 5
  • 24
  • 44