如何在文本中显示json返回的变量

问题描述 投票:-4回答:2
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;
}

如何在第2行到第70行显示变量“empName”“child:Text('')”

Full code on Pastebin

dart flutter
2个回答
1
投票

试试这种方式..像这样的方式为响应数据制作pojo类..

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

为api调用make方法..

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

之后创建获取数据的全局对象..

  Future<UserData> userDataList;

点击按钮..

            userDataList = fetchData();

之后你想要打印数据..

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

0
投票

首先,你getUserData()函数永远不会返回任何东西。看起来你只需要这个名字,所以这个函数看起来像这样:

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'];
}

然后设置empName变量你应该使用setState()。所以将你的afterFirstLayout()方法更改为:

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

此外,您似乎想要按IconButton重新加载名称。所以你可能想用这个覆盖你的代码:

IconButton(icon: Icon(Icons.shopping_cart),
  onPressed:() {
    getUserData().then( (userName) {
      setState(() {
      empName = userName;
      });
    });
  },
),
© www.soinside.com 2019 - 2024. All rights reserved.