【发布时间】:2021-07-01 23:48:52
【问题描述】:
我一直在寻找一种解决方案来对FutureBuilder 内的列表(升序和降序)On Button Press 进行排序,即Future<List>,但似乎无法理解如何将其定义为列出然后按一下按钮对其进行排序。所以我调用API,API返回一些虚拟值,它在Future Builder和ListView.builder中构建,现在我想按id(或任何类型)对列表进行排序,但该方法不起作用因为列表为空。代码:
虚拟数据的 API 调用:
Future<List<Post>> fetchPosts() async {
List<Post> posts = [];
final response = await http.get('https://jsonplaceholder.typicode.com/posts');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
var postsJson = jsonDecode(response.body);
for (int i = 0; i < postsJson.length; i++) {
posts.add(Post.fromJson(jsonDecode(response.body)[i]));
}
return posts;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load posts');
}
}
未来的建设者:
List<Post> posts = []; /// if a define it like this, the value is always null
Future<List<Post>> futurePosts;
@override
void initState() {
super.initState();
futurePosts = fetchPosts();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: SafeArea(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
MaterialButton(color: Colors.grey, onPressed: (){
// here I am setting set to compare the values of all IDs so it can be sorted ascending and descending by number of ID every time I press the button
setState(() {
posts.sort((a, b) => a.id.compareTo(b.id));
});
},),
Container(
height: 1000,
child: FutureBuilder<List<Post>>(
future: futurePosts,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Text('${snapshot.data[index].id}')
},
);
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
}
return Container();
},
),
但目前我的理解和代码似乎对我不起作用。任何帮助表示赞赏,在此先感谢!
【问题讨论】:
-
似乎您需要
StreamBuilder而不是FutureBuilder,因为您多次显示数据,以便触发builder:属性回调,您很可能需要StreamController.add方法跨度> -
好吧,也许你有一个观点,但排序方法是否保持不变?这是我的问题,排序,我可以尝试
StreamBuilder... -
谢谢伙计,但是
The method 'sort' isn't defined for the type 'Future'.,因为我正在调用一个API,它是一个Future- >而不是一个List
,有什么解决方法? -
你在哪里打电话给
sort?你需要在posts类字段上调用它 -
当我在
initState()中调用 API 时,因为它是 Future- > 我必须像
Future<List<Post>> list;那样定义它,所以在我想要排序的按钮中,我获取The method 'sort' isn't defined for the type 'Future'.
标签: flutter sorting mobile flutter-layout