Flutter 从listView保存计数器值

Flutter 从listView保存计数器值,flutter,Flutter,我有一个保存产品列表对象的列表 List<ProductList> listProcuct = new List<ProductList>(); 使用这个对象,我创建了一个列表视图,使用列表“listProcuct”来映射 列表视图( 子项:listprouct.map((productos){ 返回列表块( 标题:文本(“${productos.nombre}”), 尾随:新行( mainAxisSize:mainAxisSize.min, 儿童:[ product

我有一个保存产品列表对象的列表

List<ProductList> listProcuct = new List<ProductList>();
使用这个对象,我创建了一个列表视图,使用列表“listProcuct”来映射


列表视图(
子项:listprouct.map((productos){
返回列表块(
标题:文本(“${productos.nombre}”),
尾随:新行(
mainAxisSize:mainAxisSize.min,
儿童:[
productos.count!=0?
新图标按钮(图标:新图标(图标。删除),
按下时:()=>setState(()=>productos.count-=1),)
:新容器(),
新文本(productos.count.toString()),
新图标按钮(图标:新图标(Icons.add),
按下时:()=>setState(()=>productos.count+=1),),
],
),
);
}).toList(),
),
看起来像这样

问题是我需要保存计数器值​​每个产品对象的

productos.count-=1或productos.count+=1

我已经调查过了,但我不知道如何在列表中保存对象ProductList的这些递减和递增值:

List<ProductList> listProcuct = new List<ProductList>();
List listprouct=new List();

我需要帮助:(

您正在做正确的事情来增加/减少:

onPressed: () =>setState(() =>productos.count -= 1)
因此
productos.count
将保留更新的值??否…因为
setState
也将重新触发对数据库的查询,并将
productos.count
的值刷新为其原始值…然后,您将丢失更新的值

解决方案: 您不必将值保存到
productos.count
,而是必须保存到一个新的本地数据结构中…仅使用一个本地变量
int\u count
尝试一下,看看它是如何工作的…但最有可能的是,您需要创建一个与查询结果长度相同的
列表

在您的类中,类似这样的变量:

List<int> countList=[];

使用
ListView.builder
而不是
ListView
,这样您将获得项目的位置,并可以更新列表中相应的项目

   ListView.builder(
      itemCount: listProcuct.length,
      itemBuilder: (BuildContext context, int position) {
        ProductList productos = listProcuct.elementAt(position);
        return ListTile(
          title: Text('${productos.nombre}'),
          trailing: new Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              productos.count != 0
                  ? new IconButton(
                      icon: new Icon(Icons.remove),
                      onPressed: () {
                        productos.count -= 1;
                        updateCount(productos, position);
                      },
                    )
                  : new Container(),
              new Text(productos.count.toString()),
              new IconButton(
                icon: new Icon(Icons.add),
                onPressed: () {
                  productos.count += 1;
                  updateCount(productos, position);
                },
              ),
            ],
          ),
        );
      },
    );

如果您使用的是有状态小部件,那么可变状态应该存储在构建方法之外的State类中。 为什么?因为有状态和无状态小部件是不可变的,所以不能在那里存储可变数据。 但是有状态小部件通过在一个帧到另一个帧之间保持状态来实现这一
可变性。
但是在每个帧中都会调用build方法,因此您不应该在那里创建状态,而且build函数不应该有任何副作用,因此只需将列表存储为state类的属性,如下所示:


class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<ProductList> listProduct = [
    ProductList(count: 2),
    ProductList(count: 3),
  ];


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView(children: [
          for (var productos in listProduct)
            ListTile(
              title: Text('${productos.nombre}'),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  if (productos.count != 0)
                    IconButton(
                        icon: Icon(Icons.remove),
                        onPressed: () {
                          setState(() {
                            productos.decrementCounter() ;
                          });
                        }),
                  Text(productos.count.toString()),
                  IconButton(
                    icon: Icon(Icons.add),
                    onPressed: () => setState(() => productos.count += 1),
                  ),
                ],
              ),
            )
        ]),
      ),
    );
  }
}



类MyHomePage扩展StatefulWidget{
最后的字符串标题;
MyHomePage({Key?Key,必选this.title}):super(Key:Key);
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
列表产品=[
产品列表(计数:2),
产品列表(计数:3),
];
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(widget.title),
),
正文:中(
子项:列表视图(子项:[
for(listProduct中的var productos)
列表砖(
标题:文本(“${productos.nombre}”),
尾随:行(
mainAxisSize:mainAxisSize.min,
儿童:[
如果(productos.count!=0)
图标按钮(
图标:图标(图标。删除),
已按下:(){
设置状态(){
productos.decrementCounter();
});
}),
Text(productos.count.toString()),
图标按钮(
图标:图标(Icons.add),
按下时:()=>setState(()=>productos.count+=1),
),
],
),
)
]),
),
);
}
}

请注意,我没有使用
new
关键字,因为它是可选的,只会使代码更加混乱,并且使用collection if和collection for来显示每个listTile,如果不满足条件则不必显示空容器,则使用collection with the collection。

您能说得更清楚些吗,因为更改了值(递增/递减)已反映在列表中。@Nidheesh我需要更新增量和减量值​​对于列表中存储的每个对象,因为设置状态只更新视图中的数据,不会保存它。非常感谢,这正是我要查找的!哦,我没有考虑帧。谢谢。我也尝试过这种方法,但在使用对象排序数据时,它变得更加困难,幸运的是我可以解决谢谢你的帮助
onPressed: () =>setState(() =>countList[index] -= 1)
   ListView.builder(
      itemCount: listProcuct.length,
      itemBuilder: (BuildContext context, int position) {
        ProductList productos = listProcuct.elementAt(position);
        return ListTile(
          title: Text('${productos.nombre}'),
          trailing: new Row(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              productos.count != 0
                  ? new IconButton(
                      icon: new Icon(Icons.remove),
                      onPressed: () {
                        productos.count -= 1;
                        updateCount(productos, position);
                      },
                    )
                  : new Container(),
              new Text(productos.count.toString()),
              new IconButton(
                icon: new Icon(Icons.add),
                onPressed: () {
                  productos.count += 1;
                  updateCount(productos, position);
                },
              ),
            ],
          ),
        );
      },
    );
 void updateCount(ProductList product, int position) {
    setState(() => listProcuct[position] = product);
  }

class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key? key, required this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<ProductList> listProduct = [
    ProductList(count: 2),
    ProductList(count: 3),
  ];


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ListView(children: [
          for (var productos in listProduct)
            ListTile(
              title: Text('${productos.nombre}'),
              trailing: Row(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  if (productos.count != 0)
                    IconButton(
                        icon: Icon(Icons.remove),
                        onPressed: () {
                          setState(() {
                            productos.decrementCounter() ;
                          });
                        }),
                  Text(productos.count.toString()),
                  IconButton(
                    icon: Icon(Icons.add),
                    onPressed: () => setState(() => productos.count += 1),
                  ),
                ],
              ),
            )
        ]),
      ),
    );
  }
}