How to display variable from json return in text

2019-09-29 05:12发布

问题:

String empName;
Future<List> getUserData() async{
  final response = await http.post("http://172.16.161.34:8080/ebs/cfs/android_test_app/accessfile.php?q=getUserData",body:{
    "emp_id": widget.empId,
  });
  var dataUser = jsonDecode(response.body);
  empName = dataUser[0]['name'];

  return null;
}

How to display the variable "empName" in line 2 to line 70 "child: Text('')"

Full code on Pastebin

回答1:

Try this way.. make pojo class for response data like this way..

 class UserData {
 final int albumId;
 final int id;
 final String title;
 final String url;
 final String thumbnailUrl;

 UserData({this.albumId, this.id, this.title, this.url, this.thumbnailUrl});

 factory UserData.fromJson(Map<String, dynamic> json) {
  return new UserData(
    albumId: json['albumId'],
    id: json['id'],
    title: json['title'],
    url: json['url'],
    thumbnailUrl: json['thumbnailUrl']);
 }
 }

make method for api call..

Future<UserData> fetchData() async {
 var result = await get('https://jsonplaceholder.typicode.com/photos');

 if (result.statusCode == 200) {
  return UserData.fromJson(json.decode(result.body));
 } else {
// If that response was not OK, throw an error.
throw Exception('Failed to load post');
}
}

after that make global object that fetch data..

  Future<UserData> userDataList;

on Button click ..

            userDataList = fetchData();

after that you want to print data..

userDataList.then((userData){
  print(userData.title);
});


回答2:

First of all you getUserData() function never returns anything. It seems like you only need the name so this function could look like this:

Future<String> getUserData() async{
  final response = await http.post("http://172.16.161.34:8080/ebs/cfs/android_test_app/accessfile.php?q=getUserData",body:{
    "emp_id": widget.empId,
  });
  var dataUser = jsonDecode(response.body);
  return dataUser[0]['name'];
}

Then to set the empName variable you should use setState(). So change your afterFirstLayout() method to this:

@override
void afterFirstLayout(BuildContext context) async {
  // Calling the same function "after layout" to resolve the issue.
  getUserData().then( (userName) {
    setState(() {
      empName = userName;
    });
  });
}

Also you seem to want to reload the name once you press the IconButton. So you might want to override your code with this:

IconButton(icon: Icon(Icons.shopping_cart),
  onPressed:() {
    getUserData().then( (userName) {
      setState(() {
      empName = userName;
      });
    });
  },
),


标签: dart flutter