这是JSON文件
[
{
"id": 1,
"country": "United States",
"population": 328200000
},
{
"id": 2,
"country": "Germany",
"population": 83020000
},
{
"id": 3,
"country": "United Kingdom",
"population": 66650000
}
]
我想要按RaisedButton
后,它将按顺序排序(“国家名称” =>减少;“国家人口” =>按字母顺序)(image preview)。怎么做?
这是主文件:
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)),
],
);
}
}
This正式文档将提供有关如何排序的信息。
尝试以下方法。
CountryServices.getCountry().then((value) {
setState(() {
_country = _sortedList;
_country.sort((a, b) => a.population.compareTo(b.population));
});
});
注意:上面的代码未经测试。您可能需要稍作调整。