Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

dart - How to display variable from json return in text

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...