简体   繁体   中英

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.

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.

You can use

data = jsonDecode(response.body)

For individual contents, use data["message"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM