0

I want to get my user's data from firebase. However, when I want to use the received data in the code the LateInit error appears. Here's the code:

UPDATE:

  late MyUser myUser;
  late int pointsCount, dayStreak;

  void fetchData() async {
    String? uid = Auth().currentUser?.uid.toString();
    DatabaseReference ref = FirebaseDatabase.instance.ref("users/${uid}");

    var result = await ref.get();
    final data = Map<String, dynamic>.from(result.value as Map);
    myUser = MyUser.fromMap(data);
    print('my name: ${myUser.name}');


    pointsCount = myUser.points;
    dayStreak = myUser.days_streak;
  }


  @override
  void initState() {
    super.initState();

    pointsCount = 80;
    dayStreak = 1;
    userName = Auth().currentUser!.displayName.toString();

    fetchData();
  }

The error: LateInitializationError: Field 'pointsCount' has not been initialized.

Absdqqqq
  • 43
  • 5
  • 4
    Where's your error message? – Frank nike Mar 28 '23 at 11:30
  • 4
    where is the late variable ? – Gwhyyy Mar 28 '23 at 12:10
  • Two things are wrong: 1. You check `myUser != null`, but `myUser` can *never* be `null` since it is declared with a non-nullable type. Furthermore [you cannot check if a `late` variable has been initialized](https://stackoverflow.com/q/66776596/). If you want to check that, use a nullable type. 2. The `myUser != null` check will not wait for `ref.get()` to complete. It either needs to be in the `.then()` callback, or, better, just use `await`. Prefer using `async`-`await` over `Future.then`. – jamesdlin Mar 28 '23 at 15:22
  • Can you please write that? I am not sure how I get data without using .then() – Absdqqqq Mar 28 '23 at 16:06
  • @Absdqqqq As I said use `await`: `var value = await ref.get();` – jamesdlin Mar 28 '23 at 17:04
  • @jamesdlin I followed what you said, but I still get an error. Can you please check out the updated post? – Absdqqqq Apr 02 '23 at 15:38
  • 1
    The error should give you a stack trace that indicates where you're accessing an uninitialized `late` variable. In general I recommend using `late` variables only as a last resort. If you initialize `pointsCount` and `dayStreak` to fixed values, why don't you just initialize them as field initializers at the declaration site? – jamesdlin Apr 02 '23 at 16:14

0 Answers0