sorting - Flutter:如何按降序或字母顺序对 ListView(来自 Json 的数据)进行排序?
问题描述
这是 JSON 文件
[
{
"id": 1,
"country": "United States",
"population": 328200000
},
{
"id": 2,
"country": "Germany",
"population": 83020000
},
{
"id": 3,
"country": "United Kingdom",
"population": 66650000
}
]
我希望按 后RaisedButton
,它会按顺序排序('Country Name' => reduction;'Country 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: () {}, // 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));
});
});
注意:以上代码未经测试。你可能需要稍微调整一下。
推荐阅读
- r - R维恩图问题
- python - Python 底图:使用 rgb 文件中的颜色表,而不是预定义的 Matplotlib 颜色表
- python - 如何在服务器上运行 python 脚本?
- c - 如何在不区分大小写的情况下在字符串中查找单词?
- javascript - 用 django 提供 npm 包的最佳方式?
- c++ - 函数重载和继承(为什么这不起作用?)
- swift - 更新进度时 UIProgressView 角半径发生变化
- ruby - 如何在 Ruby 中修改方法定义本身的行为
- python - 使用 Selenium 和 Python 查找要在 html 中单击的元素
- html - 如何在具有角度嵌套数据组的材料表中显示拆分标题