4

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.

2 Answers 2

2

You can use

data = jsonDecode(response.body)

For individual contents, use data["message"]

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.