在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是关于它的博客。