如何解决在Flutter中动态排序ListView
我想基于BottomNavigationBar中的StreamController对ListView进行排序。 问题是,当我单击应用程序栏上的按钮时,Listview不会刷新。
这是我的代码:
Home.dart
a,b,c,d = range(4) # the 4 on the right hand side of the expression is what I want
# to get rid of.
CompanyTab.dart
final CompanyService _companyService = CompanyService();
final AuthService _auth = AuthService();
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
Home createState() => Home();
}
class Home extends State<HomePage> {
Comparator<Company> _sortFunction;
int _currentIndex;
var _tabs = [];
@override
void initState() {
super.initState();
_currentIndex = 0;
_sortFunction = (a,b) => a.name.compareto(b.name);
}
PreferredSize getDoubleHomeAppBar() {
return PreferredSize(
preferredSize: Size.fromHeight(55.0),child: Row(
children: <Widget>[
Expanded(
child: Container(
padding: EdgeInsets.only(left: 12.0),margin:
const EdgeInsets.only(left: 12.0,bottom: 8.0,right: 12.0),color: PRIMARY_COLOR,),FlatButton.icon(
icon: Icon(Icons.sort_by_alpha),label: Text(
'Sort',onpressed: () {
setState(() {
_sortFunction = (a,b) => b.city.compareto(a.city);
_tabs[0] = CompanyTab(sortFunction: _sortFunction);
});
},],));
}
@override
Widget build(BuildContext context) {
_tabs = [
CompanyTab(sortFunction: _sortFunction),MapTab(),Center(child: Text('Profile')),Center(child: Text('Settings')),];
return Scaffold(
backgroundColor: BACKGROUND_COLOR,appBar: AppBar(
elevation: 0.0,centerTitle: true,title: Text(
'JobAdvisor',style: TextStyle(
fontSize: MediaQuery.of(context).size.height / 24,fontWeight: FontWeight.bold,color: Colors.white,bottom: _currentIndex == 0 ? getDoubleHomeAppBar() : null,actions: <Widget>[...],body: _tabs[_currentIndex],bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,backgroundColor: BACKGROUND_COLOR,type: BottomNavigationBarType.fixed,items: [
...
],onTap: (index) {
setState(() {
_currentIndex = index;
print('Index: $index');
print('Current index: $_currentIndex');
});
},);
}
}
解决方法
我认为问题出在您的排序方法上。应该是这样的:
_sortFunction.sort((a,b) => a.name.compareTo(b.name));
您可以从official document阅读。
编辑:
您需要在此处使用小部件的sortFunction:
tmp.sort(widget.sortFunction);
您没有在CompanyTab中使用相同的sortFunction。您应该使用参数附带的sortFunction。 Here是关于它的博客。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。