-2

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.

leauradmin
  • 321
  • 2
  • 11
  • 1
    I would suggest to read about asynchronous programming and what Futures are in Dart. This is an asynchronous call and you need to wait for the result to have what you want. Check this doc please for more information. https://dart.dev/codelabs/async-await – salihgueler Feb 15 '22 at 13:49
  • Does this answer your question? [What is a Future and how do I use it?](https://stackoverflow.com/questions/63017280/what-is-a-future-and-how-do-i-use-it) – nvoigt Feb 15 '22 at 14:38

1 Answers1

1

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;
liam spiegel
  • 520
  • 5
  • 18