0

So, I have a user model where i want to store the value from the document present in firestore and for that i have the following code:-

import 'package:cloud_firestore/cloud_firestore.dart';

class UserModel
{
  final String? id;
  final String? username;
  final String? email;
  final String? url;
  final String? androidNotificationToken;

  UserModel({
    this.id,
    this.username,
    this.email,
    this.url,
    this.androidNotificationToken,
  });

  factory UserModel.fromDocument(DocumentSnapshot doc)
  {
    return UserModel(
      id: doc.data()['id'], //error
      username: doc.data()['username'],//error
      email: doc.data()['email'],//error
      url: doc.data()['url'],//error
      androidNotificationToken: doc.data()['androidNotificationToken'],//error
    );
  }
}

And the error am facing is that a red line is showing error on the square brackets after doc.data() as marked in my code. The error is:-

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

The one fix which i found was to replace doc.data()['id'] with (doc.data() as dynamic)['id]. So is it the best approach?

Deepak Lohmod
  • 2,072
  • 2
  • 8
  • 18

1 Answers1

1

You should replace:

doc.data() as dynamic['id']

with:

doc.data() as Map<String, dynamic>['id']

DocumentSnapshot.data is of type Map<String, dynamic>.

Check out the migration guide for cloud_firestore 2.0.0.

Victor Eronmosele
  • 7,040
  • 2
  • 10
  • 33