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

时间:2021-07-26 13:27:06

标签: flutter 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");
    });
  }
}

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

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" 只是一个列表视图,我需要在这里粘贴我的响应代码吗?当我切换到“历史屏幕”时,我想获取所有订单历史记录,我非常感谢代码示例

1 个答案:

答案 0 :(得分:2)

您应该尝试以下代码:

您的 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();
        },
      ),
    ),
  ),