简体   繁体   English

如何将容器添加到 Flutter 中的点击列

[英]How to add a container to a column on tap in Flutter

I have a situation where I have a listview of containers, and I would like when I double tap each container another container pops up below with information.我有一个容器列表视图的情况,当我双击每个容器时,我想在下面弹出另一个容器并显示信息。 Currently what I am trying to do is wrap each container within a column and do something like: onDoubleTap() {showBox = true} , and in the column have code: children: [post(), showbox == true? infobox(): container()]目前我正在尝试做的是将每个容器包装在一个列中并执行类似的操作: onDoubleTap() {showBox = true} ,并且在列中有代码: children: [post(), showbox == true? infobox(): container()] children: [post(), showbox == true? infobox(): container()] but I am not sure of the correct implementation. children: [post(), showbox == true? infobox(): container()]但我不确定正确的实现。 Any help would be great!任何帮助都会很棒!

you should maintain a list of containers:您应该维护一个容器列表:

class ContainerAdder extends StatefulWidget {
  const ContainerAdder({Key? key}) : super(key: key);

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

class _ContainerAdderState extends State<ContainerAdder> {
  List<Widget> containers = <Widget>[];
  Random random = Random();
  List<Color> colors = [
    Colors.blue,
    Colors.green,
    Colors.red,
    Colors.orange,
    Colors.purple,
    Colors.pink,
    Colors.teal,
    Colors.yellow,
  ];

  addContainer() {
    setState(() {
      int r = random.nextInt(colors.length);
      containers.add(
        InkWell(
          onDoubleTap: () => addContainer(),
          child: Container(
            margin: const EdgeInsets.only(bottom: 1.0),
            height: 50.0,
            color: colors[r],
          ),
        ),
      );
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [...containers],
      ),
    );
  }
}

As you can notice, the method addContainer() adds a container which is wrapped in an InkWell to have the tap listener.如您所见,addContainer() 方法添加了一个容器,该容器包装在 InkWell 中以具有点击侦听器。 The doubleTap calls the method addContainer(). doubleTap 调用方法 addContainer()。

I simply spread the containers list inside ListView widget.我只是在 ListView 小部件中传播容器列表。

In the addContainer() method, I wrap the codes inside setState() so as to refresh the tree.在 addContainer() 方法中,我将代码包装在 setState() 中以刷新树。 You can use any other state management architecture if you so wish.如果您愿意,可以使用任何其他 state 管理架构。

For the first time, I call addContainer() inside initState(), in order to populate the list with the first element.我第一次在 initState() 中调用 addContainer(),以便用第一个元素填充列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM