【发布时间】:2022-01-08 15:39:03
【问题描述】:
我正在尝试使用本教程从测试 API 中获取 Flutter 中的数据 - https://flutterforyou.com/how-to-fetch-data-from-api-and-show-in-flutter-listview/
当我复制代码时VS Code抛出这个错误,我不明白,我需要做什么 enter image description here
感谢您的回复,提前对虚拟问题表示抱歉,代码示例
Future <List<Data>> fetchData() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
List jsonResponse = json.decode(response.body);
return jsonResponse.map((data) => Data.fromJson(data)).toList();
} else {
throw Exception('Unexpected error occured!');
}
}
class Data {
final int userId;
final int id;
final String title;
Data({required this.userId, required this.id, required this.title});
factory Data.fromJson(Map<String, dynamic> json) {
return Data(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
class _MyAppState extends State<MyApp> {
late Future <List<Data>> futureData;
@override
void initState() {
super.initState();
futureData = fetchData();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter API and ListView Example',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter ListView'),
),
body: Center(
child: FutureBuilder <List<Data>>(
future: futureData,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Data> data = snapshot.data;
return
ListView.builder(
itemCount: data.length,
itemBuilder: (BuildContext context, int index) {
return Container(
height: 75,
color: Colors.white,
child: Center(child: Text(data[index].title),
),);
}
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
// By default show a loading spinner.
return CircularProgressIndicator();
},
),
),
),
);
}
}
【问题讨论】:
-
更改此:列表?数据 = 快照.data;
标签: flutter dart async-await