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



我是Dart的新手,正在学习如何从互联网上获取数据。我正在使用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,我不知道为什么会出现这种情况。有人能给我一个提示吗?谢谢

您应该在您的状态中创建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);
}
}

相关内容

最新更新