Home > Software design >  Retrieved null when there is data in firestore with flutter
Retrieved null when there is data in firestore with flutter

Time:05-26

I'm working on an app's profile page that is supposed to retrieve data from firestore and show them in editable textfield or date picker or whatever.

It turns out the snapshot.data seems not to be null, but the field it gets is null when there is actually data in my firestore.

Here is my code:

  @override
  initState() {
    super.initState();
    initInfo();
  }

  initInfo() async {
    // get info from current user
    final currUser = await FirebaseAuth.instance.currentUser;
    if (currUser != null) {
      DocumentSnapshot snapshot = await FirebaseFirestore.instance
          .collection('users')
          .doc('Dv7DkLm6Ls8Q4tKuVXEq')
          .get();

      Map<String, dynamic> data = snapshot.data()! as Map<String, dynamic>;
      name = data['name'];
      profilePath = data['profilePath'];
      birthday = data['birthday'].toDate();
      anniversary = data['annversary'].toDate();
      couple = data['couple'];

      setState(() {});
    }
  }

The error is like: [VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: NoSuchMethodError: The method 'toDate' was called on null.

Receiver: null

Tried calling: toDate()

#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)

#1 _UserPageState.initInfo

And my firebase is like: firebase

CodePudding user response:

Can you just check what data you are getting in the data map with the help of log(data.toString()) or print(data.toString()).

CodePudding user response:

var birthday;
var anniversary;

  birthday = data['birthday'].toDate() ?? DateTime.now();
  anniversary = data['annversary'].toDate() ?? DateTime.now();

1st you need to check birthday,anniversary variable type make it as var . not string or DateTime ,

  • Related