简体   繁体   中英

Retrieved null when there is data in firestore with flutter

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

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

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,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM