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

6

我是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");
    });
  }
}

我没有向服务器发出请求的经验,因此除了 "print" 之外,我不知道如何在任何其他地方显示它。

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
你应该参考 https://flutter.dev/docs/cookbook/networking/fetch-data。 - Ravindra S. Patil
在示例中,他们使用了“required”,但当我尝试使用时,它显示“required不是一种类型”。也许随着更新的进行,有些变化了。我不知道这里的解决方案是什么。 - user15415235
请使用@required。 - Benedict
非常感谢,谢谢你的帮助。 - user15415235
1个回答

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

声明你的类

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

是的,我已经找到解决方案了,不过还是谢谢您。 - user15415235

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接