How can I reach a specific data from JSON response in flutter?

Viewed 1085

I am practising flutter and I need to use a data from my response in JSON format. Here is my POST request:

    final response = await http.post(url,
        headers: {"Content-type": "application/json", "accept": "/"},
        body: json.encode({
          'username': id,
          'password': pwd,
          'deviceId': devid,
        }));
    if (response.statusCode == 200) {
      check = true;
      print("OK");
    } else {
      check = false;
      print("NOT OK");
    }
    print(response.body);
  }

and my user data class:

class userData {
  String deviceId;
  String accessToken;
  String name;
  String surname;
}
userData globaluserData;

These are two seperate .dart files. So, in my response, I get those datas, but how can I make it like -globaluserData.name = response.name- I did some research but to be honest I could not understand and adapt solutions to my project. Thanks in advance!

2 Answers

You can convert your response into JSON and then access the data like a dictionary.

if (response.statusCode == 200) {
  var jsonResponse = jsonDecode(response.body);

  globaluserData.name = jsonResponse['name']
} else {
...

You can use the app state provider to access a variable in the whole project. Your provider will look like this:

import 'package:flutter/material.dart';

class AppStateProvider extends ChangeNotifier {
  UserData _currentUser;

  void setCurrentUser(UserData currentUser) {
    _currentUser = currentUser;

    //Call this whenever there is some change in any field of change notifier.
    notifyListeners();
  }


  //Getter for current user 
  UserData get currentUser => _currentUser;
}

You can read more from here.

Related