如何在扑朔迷离中重建所有网格项目? [英] How to rebuild all grid items in flutter?

查看:58
本文介绍了如何在扑朔迷离中重建所有网格项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a dashboard, represented by grid, that supposed to delete item on long press event (using flutter_bloc), but it deletes last item instead of selected. All debug prints show, that needed element actually removed from list, but view layer still keeps it.

我的构建功能代码:

  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
              );
            }
          }
      })
    );
  }

完整的类代码仪表板块

看起来像网格会自行重建,但不重建其磁贴.如何使用其所有子组件完全更新网格小部件?

Looks like grid rebuilds itself, but don't rebuild its tiles. How can I completely update grid widget with all its subwidgets?

附言:我花了两天时间对其进行修复,请帮助

p.s i've spent two days fixing it, pls help

推荐答案

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

I think you should use a GridView.builderconstructor to specify a build function which will update upon changes in the list of items, so when any update occur in your data the BlocBuilder will trigger the build function inside yourGridView.

我希望这个例子更加清楚.

I hope this example makes it more clear.

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,
          );
        },
      ),
    );
  }
}

这篇关于如何在扑朔迷离中重建所有网格项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆