Home > Enterprise >  LateInitializationError: Field 'user' has not been initialized
LateInitializationError: Field 'user' has not been initialized

Time:05-18

I have problem with user initial value.

I have this type of source codes: "https:// paste.ofcode.org/ycHT4YFsDGSQXa68JiKJRH"

important lines in links:

  child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: 240,
                  child: FutureBuilder(
                      future: getCurrentUser(),
                      builder: (context, snapshot) {
                        return ListView.separated(
                          itemBuilder: (context, index) {
                            print(index);
                            return GetUserName(documentId: user?.uid);
                          },
                          separatorBuilder: (context, index) {
                            return SizedBox(width: 10);
                          },
                          itemCount: myCards.length,
                          shrinkWrap: true,
                          scrollDirection: Axis.horizontal,
                        );
                      }),

I have this class also,

class GetUserName extends StatelessWidget {
  final String documentId;
  final int index = 0;

  GetUserName({
    required this.documentId,
  });

  @override
  Widget build(BuildContext context) {
    // get the collection
    CollectionReference users = FirebaseFirestore.instance.collection('Users');

    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data =
              snapshot.data!.data() as Map<String, dynamic>;
          return MyCard(
            userName: data['username'],
            card: myCards[index],
          );
          //  Text('First Name: ${data['username']}');

        } else {
          print("here");
          return MyCard(
            userName: "Waiting",
            card: myCards[index],
          );
        }
        return Text('loading..');
      },
    );
  }
}

I am using FutureBuilder in 90th line and its future value is getCurrentUser() this function create this value user = await _auth.currentUser;

and I give the user?.uid parameter in GetUserName function in line 96 (purpose: give current user id to GetUserName).

I see succesfuly current user name in MyCard but also I've erorr

======== Exception caught by widgets library =======================================================
The following LateError was thrown building:
LateInitializationError: Field 'user' has not been initialized.

How can I solve this problem ?

CodePudding user response:

Use User? user instead of late final userto be able to check for a null value before the user has been loaded. And in your getCurrentUser() method when the user is fetched, use setState to update the user and the current state:

Future getCurrentUser() async {
  final loadedUser = await _auth.currentUser;

    if (loadedUser != null) {
      setState(() {
        user = loadedUser;
      });
    }
}
  • Related