Search code examples
flutterbuttongroup

How can I implement selecting only one button from group buttons in flutter


I have added a picture of what I plan to implement. It's a group button where you can only select one option at a time. I used a package called "group_button" but it allows multiple selection at a time which isn't what I want.

Recommend an alternative means of achieving this.

Picture of what I plan to implement


Solution

  • A fully working example for this:

    class T extends StatefulWidget {
      const T({Key? key}) : super(key: key);
    
      @override
      _TState createState() => _TState();
    }
    
    class _TState extends State<T> {
      List<bool> isCardEnabled = [];
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('T'),
          ),
          body: GridView.builder(
            padding: const EdgeInsets.all(15),
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 3,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10
              ),
              itemCount: 4,
              itemBuilder: (BuildContext context, int index){
                isCardEnabled.add(false);
                return GestureDetector(
                    onTap: (){
                      isCardEnabled.replaceRange(0, isCardEnabled.length, [for(int i = 0; i < isCardEnabled.length; i++)false]);
                      isCardEnabled[index]=true;
                      setState(() {});
                    },
                    child: SizedBox(
                      height: 40,
                      width: 90,
                      child: Card(
                        color: isCardEnabled[index]?Colors.cyan:Colors.grey.shade200,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8)
                        ),
                        child: Center(
                          child: Text('Ability Tag',
                            style: TextStyle(
                                color: isCardEnabled[index]?Colors.white:Colors.grey,
                              fontSize: 18
                            ),
                          ),
                        ),
                      ),
                    )
                );
              }),
        );
      }
    }