skip to Main Content

i have been trying to solve this error , after i login i was getting type ‘Null’ is not a subtype of type ‘String’ for about 5 seconds and after that the app successfully login, i do not know why this happen, i already add null check to the User but i still get the error . Below is my code, tell me if you need more info, Thanks for helping

class _controState extends State<contro> {
  _controState();
  User? user = FirebaseAuth.instance.currentUser;
  UserModel loggedInUser = UserModel();
  var role;
  var email;
  var id;
  @override
  void initState() {
    super.initState();
    FirebaseFirestore.instance
        .collection("users") //.where('uid', isEqualTo: user!.uid)
        .doc(user!.uid)
        .get()
        .then((value) {
      this.loggedInUser = UserModel.fromMap(value.data());
    }).whenComplete(() {
      CircularProgressIndicator();
      setState(() {
        email = loggedInUser.email.toString();
        role = loggedInUser.role.toString();
        id = loggedInUser.uid.toString();
      });
    });
  }

  routing() {
    if (role == 'Freelancer') {
      return JobScreen(
        id: id,
      );
    } else {
      return JobScreenClient(
        id: id,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    CircularProgressIndicator();
    return routing();
  }
}

2

Answers


  1. inside your routing, role might be null before FirebaseFirestore's result get ready, try this:

    routing() {
        if(role == null){
         return Container(); // show empty widget like this or what widget you want
        }else if (role == 'Freelancer') {
          return JobScreen(
            id: id,
          );
        } else {
          return JobScreenClient(
            id: id,
          );
        }
    }
    
    Login or Signup to reply.
  2. You have to add async/await to your code, because it’s future functions..

    void initState() async {
        super.initState();
        await FirebaseFirestore.instance
            .collection("users") //.where('uid', isEqualTo: user!.uid)
            .doc(user!.uid)
            .get()
            .then((value) {
          this.loggedInUser = UserModel.fromMap(value.data());
        }).whenComplete(() {
          CircularProgressIndicator();
          setState(() {
            email = loggedInUser.email.toString();
            role = loggedInUser.role.toString();
            id = loggedInUser.uid.toString();
          });
        });
      }
    
    routing() {
        if(role == null){
         return const Center(child: CircularProgressIndicator());
        }else if (role == 'Freelancer') {
          return JobScreen(
            id: id,
          );
        } else {
          return JobScreenClient(
            id: id,
          );
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search