[英]Flutter: How to sort ListView (data from Json) in decreasing order or alphabetically?
这是 JSON 文件
[
{
"id": 1,
"country": "United States",
"population": 328200000
},
{
"id": 2,
"country": "Germany",
"population": 83020000
},
{
"id": 3,
"country": "United Kingdom",
"population": 66650000
}
]
我希望在按下RaisedButton
后,它会按顺序排序(“国家名称”=> 减少;“国家人口”=> 按字母顺序)(图像预览)。 怎么做?
这是主文件:
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: () {}, // Sort alphabetically
)),
Expanded(
flex: 1,
child: RaisedButton(
child: Text('Country Population'),
onPressed: () {}, // 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)),
],
);
}
}
本官方文档将提供如何排序的信息。
试试下面的。
CountryServices.getCountry().then((value) {
setState(() {
_country = value;
_country.sort((a, b) => a.population.compareTo(b.population));
});
});
注意:以上代码未经测试。 你可能需要稍微调整一下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.