Home > Software design >  How can I implement selecting only one button from group buttons in flutter
How can I implement selecting only one button from group buttons in flutter

Time:02-18

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

CodePudding user response:

Never used that package but by looking on they pub.dev page I can see following.

Now you can use even simpler constructors to build your button groups. Example for a group with a single value selection:

GroupButton.radio(
  buttons: ['12:00', '13:00', '14:00'],
  onSelected: (i) => debugPrint('Button $i selected'),
)

Link: https://pub.dev/packages/group_button#cant-easier-to-use

CodePudding user response:

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
                        ),
                      ),
                    ),
                  ),
                )
            );
          }),
    );
  }
}
  • Related