First, my English is clearly not perfect : I will do my best ! I'm quite new with Flutter. The main idea is to get users of my application to the good screen, depending on his role. All users are stored in a FireStore Database. My problem is that the setState function seems to be called multiple times. If user is not null, I want to read the "role" field of the user in the database and then, depending on his role, I want him to be redirected to the admin page or on the client page. To resume, I just want to read one time the role and then redirect. But as I said before, if I put a print in the setState, it is called multiple times… What can I do to fix that ?
Thanks !
@override
Widget build(BuildContext context) {
User user= Provider.of<User>(context);
final AuthService _auth=AuthService();
if(user ==null){
return SignIn();
} else{
getRoleWrapper(user).then((s) {
setState(() {
user.setRole(s);
});
});
if(user.role=="administrateur"){
return PageTestAdmin();
}else{
return BasicClient();
}
}
}
}
Future<String> getRoleWrapper (User user) async{
final AuthService _auth=AuthService();
String role=await _auth.getRole(user);
return role;
}
What you want to do is to add the redirection inside the .then code so that it is run as soon as setRole is done. You don't need a setState inside there because there is no use for it. The reason why setState is run multiple times is because whenever setState is called, the Widget build(...) function is run again therefore you are entering an infinite loop. Take out setState and redirect as soon as role is determined. I think that will solve your problem. The code you need is below. Please vote and accept this as the answer (click check mark) if this solves your problem.
One more point of correction. You will likely have to initialize your user variable and _auth variable outside the build function. In Dart/Flutter, after setState, the entire build is run again and so those variables cannot be used outside the build function. Consider initializing those variables inside @override initState(...) function.
User user;
AuthService _auth;
bool isLoaded = false;
@override
void initState() {
super.initState();
user = Provider.of<User>(context);
AuthService _auth = AuthService();
}
@override
Widget build(BuildContext context) {
if (!isLoaded) {
if(user == null){
return SignIn();
}
else {
getRoleWrapper(user, _auth).then((s) {
user.setRole(s);
setState(() {
isLoaded = true;
});
});
}
}
return isLoaded ?
user.role == "administrateur" ?
PageTestAdmin() : BasicClient()
:
Container();
}
Future<String> getRoleWrapper (User user, AuthService auth) async{
String role = await auth.getRole(user);
return role;
}