首页 > 解决方案 > 如何从 Flutter 中的列表视图子项中单独获取数据?

问题描述

我创建了一个显示数据的活动,例如购物应用程序,其中产品在左侧,+ 和 - 符号在右侧。

我创建了一个新类来创建 + 和 - 以便它们可以在主类中单击和调用时独立工作。

class Counter extends StatefulWidget {


  @override
  CounterState createState() => new CounterState();
}

class CounterState extends State<Counter> {

  int itemCount = 0;

  int totalCost= 0;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100.0,
        alignment: Alignment.center,
        child:  Row(
          children: <Widget>[
            itemCount!=0 ?new IconButton(icon: new Icon(Icons.remove_circle_outline, size: 30.0,
            ),
                onPressed: (){
                  setState(()=>itemCount--);
                }
            ) :new Container(),

            new Text(itemCount.toString(), style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),),

            new IconButton(icon: new Icon(Icons.add_circle_outline, size: 30.0,
            ),
            onPressed: () {
              setState(() => itemCount++);
            }
            )
          ],
        ),
      );
  }
}

现在,如何将每个产品的计数器数据单独传递,以便我可以知道哪个产品被选择了多少次到我这样调用的类。

child: new ListView(
             children: new List.generate(1, (i)=> Counter()
    )                                                                               

标签: flutterflutter-layout

解决方案


有很多方法可以做到这一点。我推荐的方法是让父小部件存储主状态,并将其事件处理程序作为参考传递给子小部件,并在需要时让子小部件更新方法。

所以在父小部件上,你可以这样做

  var cart = List<Item>; // Create a model where you can store the items 

  void _handleCartChanges(Item newValue) {
    setState(() {
      cart.addValue(newValue) // do your stuff with the newvalue 
    });
  }

child: new ListView(
             children: new List.generate(1, (i)=> Counter(onPressed:_handleCartChanges)
    )   

现在您可以致电onPressed父母通知更改

class Counter extends StatefulWidget {
  Counter({Key key,  @required this.onPressed})
      : super(key: key);

  final bool active;
  final ValueChanged<Item> onPressed;

  void _handlePress(int value) {  
    var item = Item(...) // create an item with the new vlaues
    onPressed(item); // and pass it
  }

因此,每当您设置计数器值时,也要通知父级

 onPressed: (){
                  setState(()=>itemCount--);
                  _handlePress(itemCount) // call the parent 
                }

这不是一个有效的代码,但现在您知道如何在父子之间传递状态了。


推荐阅读