Noah_J.C_Lee
Noah_J.C_Lee

Reputation: 177

Flutter how to pick single value inside List

hi I know it is quite weird question but I've tried for a hour to solve, but wasn't able to

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(),
    ],
  ),
);

}

so if u can see in the code that user can choose several 'values[index]', if it's tapped add tapped 'values[index]' to the list. if the list contains 'value[index]' the color changes to amber and shows that these containers are chose

but now i want change this logics to choose only one single 'values[index]'

Upvotes: 0

Views: 711

Answers (1)

You can try like this, first save your selected index into variable on setState

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

then, set your ternary condition like this

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

Upvotes: 1

Related Questions