Dart-HTTP状态码200,但响应正文为空

时间:2020-08-10 02:26:31

标签: http flutter dart

我是Dart的新手,我正在学习有关从Internet提取数据的知识。我正在使用https://picsum.photos/进行练习,下面是代码的一部分。

String picture;

class GalleryPage extends StatefulWidget {
  @override
  _GalleryPageState createState() => _GalleryPageState();
}

class _GalleryPageState extends State<GalleryPage> {
  Future<String> fetchPictures() async {
    final response = await http.get('https://picsum.photos/id/0/info');

    if (response.statusCode == 200)
      return picture = response.body;
    else
      throw Exception('Failed to load pictures');
  }

  @override
  Widget build(BuildContext context) {
    print(pictures);
    return Container();
  }
}

我尝试将请求发送到VSCode中的http文件中,以下是响应的一部分。

HTTP/1.1 200 OK
Date: Mon, 10 Aug 2020 02:23:57 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: close
Content-Encoding: gzip

{
  "id": "0",
  "author": "Alejandro Escamilla",
  "width": 5616,
  "height": 3744,
  "url": "https://unsplash.com/photos/yC-Yzbqy7PY",
  "download_url": "https://picsum.photos/id/0/5616/3744"
}

但是,print语句的结果为null,我不知道为什么会这样。有人可以给我一个提示吗?谢谢。

1 个答案:

答案 0 :(得分:1)

您应该在自己的状态下创建picture字符串,然后在fetchPictures()中调用initState

class GalleryPage extends StatefulWidget {
  @override
  _GalleryPageState createState() => _GalleryPageState();
}

class _GalleryPageState extends State<GalleryPage> {
  String picture;

  Future<String> fetchPictures() async {
    final response = await http.get('https://picsum.photos/id/0/info');

    if (response.statusCode == 200)
      picture = response.body;
      print(picture); // print here
      setState(() {});
    else
      throw Exception('Failed to load pictures');
  }

  @override
  void initState() {
    super.initState();
    fetchPictures();
  }

  @override
  Widget build(BuildContext context) {
    return picture == null
             ? Center(child: CircularProgressIndicator())
             : Text(picture);
  }
}