简体   繁体   中英

Flutter : Future inside another Future

In my flutter app I have some nested Future jobs to perform. For an example, I first need to the current user's email from Firebase and then based on the email I get, pull the correct user from the database.

This I have implemented in below

class LoadSellAdsUIState extends State<LoadSellAdsUI> {
  FirebaseUser firebaseUser;
  User user;
  bool startUILoad=false;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    Future.wait([
      FirebaseJobs.getCurrentUser().then((firebaseUserTemp) {
        if (firebaseUserTemp != null) {
          firebaseUser = firebaseUserTemp;

          DataFetch()
              .loadUser(AppNavigation.getAPIUrl() +"user/getUserByEmail/" +firebaseUser.email)
              .then((User userTemp) {

                if(user!=null)
                {
                    user = userTemp;
                    print(user.email + " : " + user.iduser.toString());
                }

              setState(() {
                startUILoad=true;
              });

          });
        }
      })
    ]);
  }
//other code here
}

My Future s are defined in another class, below are the code of the above mentioned Future s

static final FirebaseAuth _auth = FirebaseAuth.instance;

static Future<FirebaseUser> getCurrentUser()
  {
    return _auth.currentUser();

  }

Future<User> loadUser(String url) async {
    final response = await http.get(url);

    if (response.statusCode == 200) {
      return User.fromJson(convert.json.decode(response.body));
    } else {
      throw Exception('Failed to load post');
    }
  }

Please note I am using the Future inside an initState method.

The issue is the code never waits for the inner Future ( DataFetch().loadUser() )) and it always move to the build method.

How can I fix this issue?

I solved this issue with a help of a boolean to monitor the states of Future . The code is below

@override
  void initState() {
    // TODO: implement initState
    super.initState();



       //IF THE USER IS NOT LOGGED IN, DIRECT THE USER TO LOGIN
      FirebaseJobs.getCurrentUser().then((firebaseUser){
        if(firebaseUser==null)
        {
          setState(() {
              startUILoad=true;
            });
        }
        else{

          firebaseUser1 = firebaseUser;
          DataFetch().loadUser(AppNavigation.getAPIUrl()+"user/getUserByEmail/"+firebaseUser.email).then((User result)
          {


            user = result;
            setState(() {
              startUILoad=true;
            });
          });
        }
      });


  }

@override
  Widget build(BuildContext context) {
    // TODO: implement build
    return startUILoad? sellAdFutureBuilder() : Center(child: CircularProgressIndicator(),);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM