How do I getter my request in flutter?

Asked

Viewed 86 times

0

I have a function that performs login and I need to save the token on storage:

  login() async {

    setState(() { isLoading = true; });
     
    final response = await http.post('https://xxx.net/api/login', 
    body: {
      "email": emailController.text,
      "senha": senhaController.text,
    });

    if (response.statusCode == 202) {
      Toast.show("Login ok", context, duration: Toast.LENGTH_LONG, gravity:  Toast.CENTER);
      // Write value 
      await storage.write(key: 'token', value: response.body.token);
    } else {
      Toast.show("Email ou senha incorreto", context, duration: Toast.LENGTH_LONG, gravity:  Toast.CENTER);
    }

    setState(() { isLoading = false; });
  }

However, I’m getting:

The getter 'token' isn’t defined for the class 'String'. Try importing the library that defines 'token', correcting the name to the name of an existing getter, or Defining a getter or field named 'token'

How can I make a getter for my Sponse?

1 answer

1


The response that you get from the request does not have the attribute token that is trying to access. In this case what should be done is to convert the body and thus obtain a map with the values that its API send (your token comes in this object).

Note: Do not forget to import the dart.convert to the archive.

Example

 login() async {

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

 final response = await http.post('https://xxx.net/api/login', 
 body: {
   "email": emailController.text,
   "senha": senhaController.text,
 });

 if (response.statusCode == 202) {
   Toast.show("Login ok", context, duration: Toast.LENGTH_LONG, gravity:  Toast.CENTER);
   // Write value

   //==== ADD ====
   var mapResponse = json.decode(response.body);
   var token = mapResponse["token"];
   //=============

   await storage.write(key: 'token', value: token);
 } else {
   Toast.show("Email ou senha incorreto", context, duration: Toast.LENGTH_LONG, gravity:  Toast.CENTER);
 }

 setState(() { isLoading = false; });
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.