Flutter 在flatter中动态排序ListView

Flutter 在flatter中动态排序ListView,flutter,listview,dart,comparable,stream-builder,Flutter,Listview,Dart,Comparable,Stream Builder,我想根据BottomNavigationBar中的StreamController对ListView进行排序。 问题是,当我单击应用程序栏上的按钮时,Listview不会刷新 我想将用户选择的功能(公司的可比性)作为参数传递 这是我的密码: 霍姆·达特 final CompanyService _companyService = CompanyService(); final AuthService _auth = AuthService(); class HomePage extends S

我想根据BottomNavigationBar中的StreamController对ListView进行排序。 问题是,当我单击应用程序栏上的按钮时,Listview不会刷新

我想将用户选择的功能(公司的可比性)作为参数传递

这是我的密码:

霍姆·达特

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');
          });
        },
      ),
    );
  }
}
final CompanyService\u CompanyService=CompanyService();
最终AuthService_auth=AuthService();
类主页扩展了StatefulWidget{
主页({Key}):超级(Key:Key);
Home createState()=>Home();
}
类主扩展状态{
比较器_sort函数;
int currentIndex;
var _tabs=[];
@凌驾
void initState(){
super.initState();
_currentIndex=0;
_sortFunction=(a,b)=>a.name.compareTo(b.name);
}
PreferredSize getDoubleHomeAppBar(){
返回首选大小(
首选尺寸:尺寸。从高度(55.0),
孩子:排(
儿童:[
扩大(
子:容器(
填充:仅限边缘设置(左:12.0),
保证金:
仅限常数边集(左:12.0,下:8.0,右:12.0),
颜色:原色,
),
),
FlatButton.icon(
图标:图标(图标。按字母排序),
标签:文本(
“排序”,
),
已按下:(){
设置状态(){
_排序函数=(a,b)=>b.city.compareTo(a.city);
_制表符[0]=公司选项卡(排序功能:\u排序功能);
});
},
),
],
));
}
@凌驾
小部件构建(构建上下文){
_制表符=[
CompanyTab(sortFunction:_sortFunction),
MapTab(),
居中(子项:文本(“配置文件”),
居中(子项:文本(“设置”),
];
返回脚手架(
背景颜色:背景颜色,
appBar:appBar(
标高:0.0,
标题:对,
标题:正文(
“工作顾问”,
样式:TextStyle(
fontSize:MediaQuery.of(context).size.height/24,
fontWeight:fontWeight.bold,
颜色:颜色,白色,
),
),
底部:_currentIndex==0?getDoubleHomeAppBar():null,
行动:[……],
),
正文:_制表符[_currentIndex],
底部导航栏:底部导航栏(
currentIndex:_currentIndex,
背景颜色:背景颜色,
类型:BottomNavigationBarType.fixed,
项目:[
...
],
onTap:(索引){
设置状态(){
_currentIndex=索引;
打印('Index:$Index');
打印('当前索引:$_currentIndex');
});
},
),
);
}
}
公司选项卡

@immutable
class CompanyTab extends StatefulWidget {
  final CompanyService _companyService = CompanyService();
  final Comparator<Company> sortFunction;

  CompanyTab({Key key, this.sortFunction}) : super(key: key);

  @override
  _CompanyTabState createState() =>
      _CompanyTabState(_companyService, sortFunction);
}

class _CompanyTabState extends State<CompanyTab> {
  StreamController<List<Company>> _streamController;
  final CompanyService _companyService;
  Comparator<Company> sortFunction;

  _CompanyTabState(this._companyService, this.sortFunction);

  @override
  void initState() {
    super.initState();
  }

  StreamBuilder companyList() {
    return StreamBuilder<List<Company>>(
        initialData: [],
        stream: _streamController.stream,
        builder: (BuildContext context, AsyncSnapshot<List<Company>> snapshot) {
          if (snapshot.hasError) {
            return Text("Something went wrong");
          }

          if (snapshot.connectionState == ConnectionState.waiting ||
              snapshot.connectionState == ConnectionState.none ||
              snapshot.data == null) {
            return LoadingWidget();
          } else {
            return ListView.builder(
                padding: const EdgeInsets.all(10),
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  Company company = snapshot.data.elementAt(index);

                  ...
                }
          }
        });
  }

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  void _getData() {
    _streamController = new StreamController<List<Company>>();
    _companyService.getCompanies().then((value) => {_elaborateList(value)});
  }

  void _elaborateList(List<Company> list) {
    List<Company> tmp = list;
    tmp.sort(sortFunction);
    print(tmp.toString());
    _streamController.sink.add(tmp);
  }

  @override
  Widget build(BuildContext context) {
    _getData();
    return Center(
      child: Container(
        child: companyList(),
      ),
    );
  }
}
@不可变
类CompanyTab扩展StatefulWidget{
最终公司服务_CompanyService=CompanyService();
最终比较器排序函数;
CompanyTab({Key-Key,this.sortFunction}):super(Key:Key);
@凌驾
_CompanyAbstrate createState()=>
_公司摘要(公司服务,sortFunction);
}
类_CompanyTabState扩展状态{
StreamController\u StreamController;
最终公司服务——公司服务;
比较器排序函数;
_companytabsate(this.\u companyService,this.sort函数);
@凌驾
void initState(){
super.initState();
}
StreamBuilder公司列表(){
返回流生成器(
初始数据:[],
流:_streamController.stream,
生成器:(BuildContext上下文,异步快照){
if(snapshot.hasError){
返回文本(“出错”);
}
如果(snapshot.connectionState==connectionState.waiting||
snapshot.connectionState==connectionState.none||
snapshot.data==null){
返回LoadingWidget();
}否则{
返回ListView.builder(
填充:常量边集。全部(10),
itemCount:snapshot.data.length,
itemBuilder:(构建上下文,int索引){
公司=快照.data.elementAt(索引);
...
}
}
});
}
@凌驾
无效处置(){
_streamController.close();
super.dispose();
}
void_getData(){
_streamController=新的streamController();
_companyService.getcompanys().then((值)=>{u detailelist(值)});
}
作废清单(清单){
列表tmp=列表;
tmp.sort(sort函数);
打印(tmp.toString());
_streamController.sink.add(tmp);
}
@凌驾
小部件构建(构建上下文){
_getData();
返回中心(
子:容器(
子项:companyList(),
),
);
}
}

我认为问题在于您的排序方法。它应该是这样的:

     _sortFunction.sort((a, b) => a.name.compareTo(b.name));
你可以从报纸上读到

编辑:

您需要在此处使用小部件的sortFunction:

     tmp.sort(widget.sortFunction);

您在CompanyTab中没有使用相同的sortFunction。您应该使用作为参数的sortFunction。这是一个关于它的博客。

这是第一个问题,但是Company tab小部件无论如何都不会刷新。它工作正常。我还必须删除CompanyTab.dart中的密钥。非常感谢!那么,现在您可以接受并更新我的答案了 :)