skip to Main Content

In my code I have the part where I manage the state of the authentication in order to be able to add or not the user information however I have an exception which is thrownyour text

InitScreen.dart

`

class InitScreen extends StatefulWidget {
  const InitScreen({Key? key}) : super(key: key);

  @override
  _InitScreenState createState() => _InitScreenState();
}

class _InitScreenState extends State<InitScreen> {
  bool? _redirect;
  String? _redirectURL;

  Future<bool> _checkAuthStatus(BuildContext ctx) async {
    try {
      User? currentUser = FirebaseAuth.instance.currentUser;
      print('currentUser: $currentUser');
      if (currentUser == null) {
        _redirect = true;
        _redirectURL = "/login";
        print("Je suis revenue");
        return true;
      }
      print("--------------------");
      UserDatabaseService databaseService = UserDatabaseService();
      print("databaseService: $databaseService");
      print("currentUser.uid: ${currentUser.uid}");
      UserModel user = await databaseService.getUser(currentUser.uid);
      print("user: $user");
      if (user == null) {
        _redirect = true;
        _redirectURL = "/userinfo";
        return true;
      }
      print('/home');
      _redirectURL = "/home";
      _redirect = true;
      return true;
    } catch (err) {
      print("Dans le catch ******* $err");
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
            FutureBuilder<bool>(
              future: _checkAuthStatus(context),
              builder: (BuildContext c, AsyncSnapshot<bool> snapshot) {
                print("InitState a retourné: ${snapshot.data}");
                if (snapshot.hasData && snapshot.data!) {
                  print("InitState a retourné: ${snapshot.data}");
                  Future.delayed(const Duration(milliseconds: 250), () {
                    print("Redirect: $_redirect $_redirectURL  |");
                    if (_redirect == true) {
                      Application.router.navigateTo(
                        context,
                        _redirectURL!,
                        replace: true,
                      );
                    }
                  });
                  return Container();
                } else if (snapshot.hasError) {
                  print(snapshot.error);
                  return Text(
                    "Authentication Error",
                    style: TextStyle(
                      fontFamily: 'Varela',
                      fontSize: 28,
                      fontWeight: FontWeight.w300,
                      color: Colors.white,
                    ),
                  );
                } else {
                  return Column(
                    children: [
                      // Ajoutez ici les widgets que vous souhaitez afficher
                    ],
                  );
                }
              },
            ),
            CircularProgressIndicator(
              backgroundColor: Colors.white,
              valueColor: AlwaysStoppedAnimation<Color>(
                Color.fromARGB(255, 247, 124, 23),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

 Future<UserModel> getUser(String id) async {
    DocumentSnapshot snapshot = await _db.collection('users').doc(id).get();
    
    return UserModel.fromSnapshot(snapshot);
  }

`class UserModel {

factory UserModel.fromSnapshot(DocumentSnapshot document) {
final Map data = document.data();
return UserModel(
userId: document.id,
email: data[’email’] ?? ‘Neant’,
fullName: data[‘fullName’] ?? ‘Neant’,
phoneNo: data[‘phoneNo’],
fieldId: data[‘fieldId’],
age: data[‘age’],
city: data[‘city’],
imageUrl: data[‘imageUrl’],
location: data[‘location’],
phone: data[‘phone’],
cdiNo: data[‘cdiNo’],
);
}
}`

I am looking for a solution in order to be able to access my /home

I have this exception
type ‘Null’ is not a subtype of type ‘Map<dynamic, dynamic>’
I provided here the function of my User class also the GetUser function and the InitScreen class

2

Answers


  1. Please check this part: final Map data = document.data(); I think you are getting a null value from firebase because it doesn’t exists.

    Add a validation like:

    if (data == null) return null;
    
    Login or Signup to reply.
  2. document.data(); is returning null, perhaps when it doesn’t find a user, so you can avoid the error by using:

     final Map data = document.data() ?? {};
    

    keep in mind that you are going to have null in the properties of the UserModel

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search