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

9 http dart flutter

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

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");
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我没有向服务器请求的经验,所以我不知道如何在除“打印”之外的任何地方显示它

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),
              ),
            ],
          )
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

PS“BodyLayout”只是一个列表视图,我需要在此处传递我的响应代码吗?当我切换到“历史记录屏幕”时,我想获取所有订单历史记录,我真的很感激代码示例

Rav*_*til 5

你应该尝试下面的代码:

您的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');
  }
}
Run Code Online (Sandbox Code Playgroud)

声明你的班级

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'],
   );
 }
}
Run Code Online (Sandbox Code Playgroud)

声明你的小部件如下:

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();
        },
      ),
    ),
  ),
Run Code Online (Sandbox Code Playgroud)