【发布时间】:2023-03-26 16:46:02
【问题描述】:
我正在尝试设置一个新的排序下拉按钮,该按钮会更改从数据库中获取的条目的排序顺序。
我可以在页面加载时对列表进行排序,但我无法使用下拉选项更改排序顺序。
代码没有错误。
任何建议我需要更改以使此代码正常工作?
class NewList extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _State();
}
class _State extends State<NewList> {
static dates;
List<Entry> _entryList = [];
List<Entry> _sort = [];
StreamController<int> _postsController;
List<Option> options = [];
Option _selectedOption;
void _select(Option option) {
setState(() {
_selectedOption = option;
});
if (_selectedOption.title =='Oldest first') {
_sort.sort((a, b) {
return b.id.compareTo(a.id);
});
} else if (_selectedOption.title =='Newest first') {
_sort.sort((a, b) {
return a.id.compareTo(b.id);
});
}
}
@override
void initState() {
_postsController = new StreamController();
fetchReport();
super.initState();
}
fetchReport() {
fecthEntries(dates.id.toString(), dates.from, dates.to)
.then((value) => {
_entryList.addAll(value),
_postsController.add(1),
setState(() {})
});
}
@override
Widget build(BuildContext context) {
dates = ModalRoute.of(context).settings.arguments;
options = <Option>[
Option(
title: 'Oldest first',
Option(
title: 'Newest first',
];
_selectedOption = options[0];
return Scaffold(
appBar: AppBar(
title: Text('Title'),
actions: <Widget>[
PopupMenuButton<Option>(
onSelected: _select,
icon: Icon(Icons.sort),
itemBuilder: (BuildContext context) {
return options.map((Option option) {
return PopupMenuItem<Option>(
value: option,
child: Text(option.title),
);
}).toList();
},
),
],
),
body: StreamBuilder<int>(
stream: _postsController.stream,
builder: (BuildContext context, AsyncSnapshot<int> result) {
if (result.hasData) {
return showAll();
}
}),
);
}
Widget showAll() {
//This is where I can sort the list onload and setup the default sort
_entryList.sort((a, b) {
return b.id.compareTo(a.id);
});
return ListView.builder(
itemCount: _entryList.length,
itemBuilder: (context, index) {
final entry = _entryList[index];
return reportRow(entry, context);
},
);
}
}
class Option {
const Option({this.title});
final String title;
}
【问题讨论】:
标签: android flutter sorting dart