Flutter:如何对JSON数据源的ListView执行指定规则排序
实现国家列表的排序功能
没问题,我来帮你搞定这两个排序需求!其实核心就是在按钮的点击回调里对国家列表做排序,然后通过setState触发UI刷新,具体实现看下面:
1. 按国家名称字母序排序
给「Country Name」按钮的onPressed添加排序逻辑,利用字符串的compareTo方法实现字母顺序排序:
onPressed: () { setState(() { // 按国家名称升序(字母序)排序 _country.sort((a, b) => a.country.compareTo(b.country)); }); },
2. 按人口数值降序排序
给「Country Population」按钮的onPressed添加人口降序排序逻辑,通过交换两个对象的比较顺序实现降序:
onPressed: () { setState(() { // 按人口降序排序 _country.sort((a, b) => b.population.compareTo(a.population)); }); },
修改后的完整代码
把上面的逻辑替换到你原有的代码里,完整代码如下:
import 'dart:convert'; import 'dart:core'; import 'package:ask/country.dart'; import 'package:ask/country_service.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { List<Country> _country = []; @override void initState() { CountryServices.getCountry().then((value) { setState(() { _country = value; }); }); super.initState(); } Widget build(BuildContext context) { return new MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Country')), body: Container( child: Column(children: <Widget>[ Row(children: <Widget>[ Expanded( flex: 1, child: RaisedButton( child: Text('Country Name'), onPressed: () { setState(() { _country.sort((a, b) => a.country.compareTo(b.country)); }); }, // Sort alphabetically )), Expanded( flex: 1, child: RaisedButton( child: Text('Country Population'), onPressed: () { setState(() { _country.sort((a, b) => b.population.compareTo(a.population)); }); }, // Sort in decreasing order ))]), Container( child: ListView.builder( shrinkWrap: true, itemCount: _country.length, itemBuilder: (context, index) { return _listCountry(index); })) ])))); } _listCountry(index) { Country country = _country[index]; return Row( children: <Widget>[ Expanded( flex: 1, child: Text( country.country, textAlign: TextAlign.center, )), Expanded( flex: 1, child: Text('${country.population}', textAlign: TextAlign.center)), ], ); } }
这样点击两个按钮的时候,列表就会按照对应的规则重新排序并刷新显示啦!
内容的提问来源于stack exchange,提问作者Kel
相关产品推荐
相关产品推荐

