gpt4 book ai didi

flutter - 如何在 Flutter 应用程序屏幕中显示来自服务器的响应?

转载 作者:行者123 更新时间:2023-12-04 07:20:31 24 4
gpt4 key购买 nike

我是新手,我正在尝试在我的屏幕上显示来自服务器的响应。我从服务器获取订单历史记录并尝试在历史记录屏幕上显示它,你怎么做?

void getAllHistory() async {
http
.post(
Uri.parse(
'https://myurlblahblah'),
body: "{\"token\":\"admin_token\"}",
headers: headers)
.then((response) {
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
}).catchError((error) {
print("Error: $error");
});
}
}
我没有请求服务器的经验,所以我不知道如何在“打印”之外的任何地方显示它
class HistoryScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(),
body: BodyLayout(),
);
}

AppBar buildAppBar() {
return AppBar(
automaticallyImplyLeading: false,
title: Row(
children: [
BackButton(),
SizedBox(width: 15),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Orders history",
style: TextStyle(fontSize: 16),
),
],
)
],
),
);
}
}
PS“BodyLayout”只是一个 ListView ,我需要在此处传递我的响应代码吗?当我切换到“历史屏幕”时,我想获取所有订单历史记录,我非常感谢代码示例

最佳答案

您应该尝试以下代码:
您的 API 调用函数

  Future<Album> fetchPost() async {
String url =
'https://jsonplaceholder.typicode.com/albums/1';
var response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return Album.fromJson(json
.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
声明你的类
class Album {
final int userId;
final int id;
final String title;

Album({
this.userId,
this.id,
this.title,
});

factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
像下面这样声明你的小部件:
Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: FutureBuilder<Album>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListTile(
leading: Icon(Icons.person_outlined),
title: Text(snapshot.data.title),
),
ListTile(
leading: Icon(Icons.email),
title: Text(snapshot.data.userId.toString()),
),
ListTile(
leading: Icon(Icons.phone),
title: Text(snapshot.data.id.toString()),
),
],
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
),
),

关于flutter - 如何在 Flutter 应用程序屏幕中显示来自服务器的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68530744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com