1

我有一个由网格表示的仪表板,它应该在长按事件时删除项目(使用flutter_bloc),但它会删除最后一个项目而不是选中的项目。所有调试打印都显示,需要的元素实际上已从列表中删除,但视图层仍保留它。

我的构建功能代码:

  Widget build(BuildContext context) {
    double pyxelRatio = MediaQuery.of(context).devicePixelRatio;
    double width = MediaQuery.of(context).size.width * pyxelRatio;

    return BlocProvider(
      bloc: _bloc,
        child: BlocBuilder<Request, DataState>(
        bloc: _bloc,
        builder: (context, state) {
          if (state is EmptyDataState) {
            print("Uninit");
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          if (state is ErrorDataState) {
            print("Error");
            return Center(
              child: Text('Something went wrong..'),
            );
          }
          if (state is LoadedDataState) {
            print("empty: ${state.contracts.isEmpty}");
            if (state.contracts.isEmpty) {
              return Center(
                child: Text('Nothing here!'),
              );
            } else{
              print("items count: ${state.contracts.length}");              
              print("-------");
              for(int i = 0; i < state.contracts.length; i++){
                if(state.contracts[i].isFavorite)print("fut:${state.contracts[i].name} id:${state.contracts[i].id}");
              }
              print("--------");  

              List<Widget> testList = new List<Widget>();
              for(int i = 0; i < state.contracts.length; i++){
                if(state.contracts[i].isFavorite) testList.add(
                  InkResponse(
                  enableFeedback: true,
                  onLongPress: (){
                    showShortToast();
                    DashBLOC dashBloc = BlocProvider.of<DashBLOC>(context);
                    dashBloc.dispatch(new UnfavRequest(state.contracts[i].id));
                  },
                  onTap: onTap,
                  child:DashboardCardWidget(state.contracts[i])
                  )
              );
              }
              return GridView.count(
                  crossAxisCount: width >= 900 ? 2 : 1,
                  padding: const EdgeInsets.all(2.0),
                  children: testList
              );
            }
          }
      })
    );
  }

完整的类代码仪表板块

看起来网格会自行重建,但不要重建其瓷砖。如何完全更新网格小部件及其所有子小部件?

ps我花了两天时间修复它,请帮助

4

4 回答 4

3

我认为您应该使用GridView.builder构造函数来指定构建函数,该函数将根据项目列表中的更改进行更新,因此当您的数据中发生任何更新时,BlocBuilder将触发GridView.

我希望这个例子更清楚。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Test(),
    );
  }
}

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  List<int> testList = List<int>();

  @override
  void initState() {
    for (int i = 0; i < 20; i++) {
      testList.add(i);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      floatingActionButton: FloatingActionButton(
        //Here we can remove an item from the list and using setState
        //or BlocBuilder will rebuild the grid with the new list data
        onPressed: () => setState(() {testList.removeLast();})
      ),
      body: GridView.builder(
        // You must specify the items count of your grid
        itemCount: testList.length,
        // You must use the GridDelegate to specify row item count
        // and spacing between items
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5,
          childAspectRatio: 1.0,
          crossAxisSpacing: 1.0,
          mainAxisSpacing: 1.0,
        ),
        // Here you can build your desired widget which will rebuild
        // upon changes using setState or BlocBuilder
        itemBuilder: (BuildContext context, int index) {
          return Text(
            testList[index].toString(),
            textScaleFactor: 1.3,
          );
        },
      ),
    );
  }
}
于 2020-02-12T01:41:46.013 回答
0

给孩子一把钥匙

 return  GridView.builder(
                itemCount: children.length,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(3),
                itemBuilder: (context, index) {
                  return Container(
                    key: ValueKey(children.length+index),                       
                  );
                });
于 2020-12-17T04:53:54.830 回答
0

真的是重建了吗?我只是不明白您为什么将 State 与BLoC一起使用。即使您使用State,您也应该调用setState()方法来使用新数据更新小部件。在我看来,最好的解决方案是尝试从StatelessWidget继承您的小部件并调用dispatch(new UpdateRequest()); DashBLOC构造函数中。

还要记住这个关于 的链接bloc,有很多例子: https ://felangel.github.io/bloc/#/

于 2019-09-22T13:42:48.370 回答
0

您的代码始终发送 int i 的最后一个值。

所以而不是

for(int i = 0; i < state.contracts.length; i++){
            if(state.contracts[i].isFavorite) testList.add(
              InkResponse(
              enableFeedback: true,
              onLongPress: (){
                showShortToast();
                DashBLOC dashBloc = BlocProvider.of<DashBLOC>(context);
                dashBloc.dispatch(new UnfavRequest(state.contracts[i].id));
              },
              onTap: onTap,
              child:DashboardCardWidget(state.contracts[i])
              )
          );

          List<Widget> testList = new List<Widget>();

          state.contracts.forEach((contract){
            if(contract.isFavorite) testList.add(
              InkResponse(
              enableFeedback: true,
              onLongPress: (){
                showShortToast();
                DashBLOC dashBloc = BlocProvider.of<DashBLOC>(context);
                dashBloc.dispatch(new UnfavRequest(contract.id));
              },
              onTap: onTap,
              child:DashboardCardWidget(contract)
              )
          ));
于 2019-04-05T16:29:11.937 回答