【问题标题】:Flutter how to pick single value inside List颤动如何在列表中选择单个值
【发布时间】:2022-01-12 07:50:31
【问题描述】:

您好,我知道这是一个很奇怪的问题,但我已经尝试了一个小时来解决,但无法解决

Expanded timePicker(BuildContext context, value) {
return Expanded(
  child: Wrap(
    spacing: 5,
    runSpacing: 10,
    direction: Axis.horizontal,
    alignment: WrapAlignment.start,
    children: [
      ...List.generate(
        value.length,
        (index) => GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            setState(() {
              if (time.contains(value[index])) {
                time.remove(value[index]);
              } else
                time.add(value[index]);
            });
          },
          child: Container(
            height: 60,
            width: MediaQuery.of(context).size.width / 5,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
              border: Border.all(
                color: time.contains(value[index]) ? Colors.amber : Colors.grey[200],
              ),
            ),
            child: Text(
              value[index],
              style: TextStyle(
                color: time.contains(value[index]) ? Colors.black : Colors.grey[200],
                fontSize: 17,
                fontWeight: FontWeight.bold,
              ),
            ),
            alignment: Alignment.center,
          ),
        ),
      ).toList(),
    ],
  ),
);

}

所以如果你可以在代码中看到 用户可以选择多个“values[index]”,如果它被点击,则将点击的“values[index]”添加到列表中。 如果列表包含“value[index]”,则颜色变为琥珀色并显示这些容器已被选中

但现在我想更改此逻辑以仅选择一个“值[索引]”

【问题讨论】:

  • 你能把你的问题说清楚吗?
  • 已修复!所以我想说的是,我怎样才能只选择一个值[index],并给出一个变化

标签: list flutter radio gesturedetector


【解决方案1】:

你可以这样试试 首先将您选择的索引保存到 setState 上的变量中

onTap: () {
   setState(() {
      selectedItem = index;
      if (time.contains(value[index])) {
         time.remove(value[index]);
      } else time.add(value[index]);
   });
          },

然后,像这样设置你的三元条件

color: index == selectedItem ? Colors.amber : Colors.grey[200],

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 1970-01-01
    • 2020-06-10
    • 2021-05-13
    • 1970-01-01
    • 2022-12-06
    • 2021-09-14
    • 1970-01-01
    • 2012-07-26
    相关资源
    最近更新 更多