Search code examples
jsonhttp-postflutter

Flutter - Http Json Response


I am trying out flutter and I have hooked up an http post for logging-in.

I created a file that will take care of my http request. In the file wrote the following codes:

Map data;

Future<Map> logIn(email, password) async {

    String url = "...";
    Object userData = { "email": email, "password": password };
    var userDataBody = JSON.encode(userData);
    Map userHeader = {"Content-type": "application/json", "Accept": "application/json"};

    http.Response response = await http.post(
                Uri.encodeFull(url), 
                headers: userHeader, 
                body: userDataBody 
    );

    data = JSON.decode(response.body);
    print(data);
    return data;
}

Http returns the following data:

{message: Login Successful, status: success}

The coded above are used in a stateful widget:

// imported the file above as userService
import 'services/user_services.dart' as userService;

// created a method for a button
void submitData() {
    final form = formKey.currentState;

    if (form.validate()) {  // no validations so far
      form.save();  // save email and password
      userService.logIn("$userEmail", "$userPassword");      // .then(JSON.decode(responseContent['message']));
    }
}

// button in container
new Container(
    padding: new EdgeInsets.all(20.0),
    child: new RaisedButton(
      onPressed: submitData,
      child: new Text('LogIn'),
    )
),

My problem is that with the returned json data, I am struggling to take the status returned (success) / message (Login Successful) and do whatever I like with them.


Solution

  • Not sure what the question is but I guess what you want is

    void submitData() async {
      ...
      var result = await userService.logIn("$userEmail", "$userPassword"); 
    }
    

    this way you can get hold of the result. There is no way to get back to sync from an async call in case this is what you're looking for.