Home > Back-end >  How to get an object from an instance of Future in Flutter?
How to get an object from an instance of Future in Flutter?

Time:02-16

I wrote the following function in order to create a User object to use it later. But the problem is that this function returns an Instance of 'Future'.I can't get the attributes of my User object.

  Future<User>?  user;

  Future<User> activerUser(String nom,String prenom,String code) async {
    final response = await http.post(
      Uri.parse('https://xxxxxxxxx'),
      headers: <String,String>{'Content-Type': 'application/json; charset=UTF-8'},
      body: jsonEncode(<String,String>{
        "nom_client":nom,
        "prenom_client":prenom,
        "num_client":code
      }),
    );
    if(response.statusCode==200){
      return User.fromJson(jsonDecode(response.body));
    }else{
      throw Exception('Echec de la creation de l'objet.');
    }
  }
if(_formKey.currentState!.validate()){
         user = activerUser(nomUesr,prenomUser,codeUser).then((obj){
         return obj;
     });
  print(user) ------>Instance of 'Future<User>';

} I'm new to the world of Flutter and Dart. Can anyone tell me how I can change from Instance of 'Future' to User instance?
thanks in advance.

CodePudding user response:

you can un future it if you add an await before the function:

await activerUser();

and if that don't work then try to add the await in the function:

return await future;
  • Related