【问题标题】:Dart - HTTP status code 200 but response body is nullDart - HTTP 状态代码 200 但响应正文为空
【发布时间】:2020-11-29 15:39:56
【问题描述】:

我是 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,我不知道为什么会这样。谁能给我一个提示?谢谢。

【问题讨论】:

  • 你在哪里打电话fetchPictures?

标签: http flutter dart


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 2015-11-16
    • 2020-12-20
    相关资源
    最近更新 更多