获取json对象并在flutter中重新加载.哦,我迷路了



我是很新的扑动和已经尝试了几天现在得到这个权利。要么我被不重新加载的设置状态卡住(使用旋转器),要么JSON代码被解码为我的示例。

我想让JSON进入listview,然后当floatingActionButton按钮被推刷新小部件与CircularProgressIndicator。这是我目前得到的。我找到的所有例子似乎都不是Null安全的,我又迷路了。

我的例子说"List'不是类型'Map<String,>"的子类型我可以看到这是因为我的JSON是一个列表列表?? ?

如能指点一下,不胜感激。

这是它提取的JSON:

[
{
"userId": 1,
"id": 1,
"title": "How to make friends"
},
{
"userId": 2,
"id": 1,
"title": "Gone with the wind"
}
]
```
Future<Album> fetchAlbum() async {
print("Fetching json....");
final response = await http.get(
Uri.parse(myLocksEp),
);
if (response.statusCode == 200) {
print(response.body);
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int id;
final String title;
Album({required this.id, required this.title});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
id: json['id'],
title: json['name'],
);
}
}
void main() {
runApp(mylocks());
}
class mylocks extends StatefulWidget {
@override
_MyAppState createState() {
return _MyAppState();
}
}
class _MyAppState extends State<mylocks> {
late Future<Album> _futureAlbum;
@override
void initState() {
super.initState();
_futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: FutureBuilder<Album>(
future: _futureAlbum,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[],
);
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
//Error message goers here
}
}
return const CircularProgressIndicator();
},
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh_outlined, color: Colors.black),
backgroundColor: Colors.grey[200],
onPressed: () {
setState(() {
_futureAlbum = fetchAlbum();
});
},
),
),
);
}
}

很抱歉写了这么长一篇文章,我希望我能说得通

提前谢谢你罗比

如果我没弄错的话,这里你提供了一个List<String,>>

return Album.fromJson(jsonDecode(response.body));

而Album.fromJson期望接收一个Map<String,动态>所以,这就是为什么你会得到错误"List'不是类型'Map<String,>">

的子类型除此之外,考虑到每次你构建小部件时,FutureBuilder总是会对你传递给它的future进行调用,所以在这种情况下,当你按下FloatingActionButton时,你会进行调用,然后,当小部件开始重建时,你会进行另一个调用。

你应该做一些调整来避免这种情况。你可以改变FloatingActionButton onPressed回调为空:

setState(() {});

再次,如果我没有错的话,这将使小部件重新构建自己,因为你说状态已经改变了,当重新构建时,FutureBuilder将发出请求,因此,更新列表。

基于注释编辑

class _MyAppState extends State<mylocks> {
late Future<Album> _futureAlbum;
//ADD ALBUMS VAR
List<Album> _albums = [];
@override
void initState() {
super.initState();
//INVOKE METHOD AND SET THE STATE OF _albums WHEN IT FINISHES
fetchAlbum().then((List<Album> albums){
setState((){_albums = albums);
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: Container(
alignment: Alignment.center,
padding: const EdgeInsets.all(8.0),
child: Column(
//REPLACE FUTURE BUILDER WITH DESIRED WIDGET, WHILE _albums IS EMPTY IT WILL RENDER A CircularProgressIndicator
children: [
_albums.isEmpty ? Center(
child: CircularProgressIndicator(),
) : ..._albums,
]
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.refresh_outlined, color: Colors.black),
backgroundColor: Colors.grey[200],
onPressed: () {
//AGAIN, WHEN FINISHING IT SHOULD REBUILD THE WIDGET AND THE DATA
fetchAlbum().then((List<Album> albums){
setState((){_albums = albums);
});
},
),
),
);
}
}

不用担心为Json创建模型,只需使用此链接自动生成模型。

最新更新