How to toggle between dynamically created RaisedButton in flutter

1

I have 4 buttons which is dynamically created based on list Value. consider I have button A,B,C & D. When i click button A color is changing from white to gray , When i click Button B or C or D... i want to revert the button A color to white and Also i want to change button color to gray which is clicked second time.

Anyone Please help me to achieve this.

Sample code is below

  return Container(
      width: double.infinity,
      child: RaisedButton(
        elevation: 10,
        color: isOptionPressed ? Color(0x4D707070) : Color(0xFFFFFFFF),
        textColor: Colors.white,
        child: Text('${list[i]}',style: TextStyle(fontSize: 16, color: Colors.black)),
        shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(50)),
        splashColor: Color(0x4D707070),
        onPressed:
             () {
                setState(() {
                    isOptionPressed = true;
                });
              },
    );
flutter
dart
asked on Stack Overflow Apr 16, 2021 by shiva

1 Answer

2

You need three basic things:

  • a way to form a list of buttons from a list of other elements:

    ListView.builder.

  • a way to save the currently selected button: onPressed and setState with a variable in your state class:

    onPressed: (){ setState(() { _selectedNumber = numbers[index]; }); },

  • a way to color your buttons according to that variable in your state class:

    numbers[index] == _selectedNumber ? Colors.green : Colors.white,

So putting it all together:

import 'package:flutter/material.dart';

const numbers = [1,2,3,4];

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: NumberSelectWidget(),
        ),
      ),
    );
  }
}

class NumberSelectWidget extends StatefulWidget {
  @override
  _NumberSelectState createState() => _NumberSelectState();
}

class _NumberSelectState extends State<NumberSelectWidget> {
  int? _selectedNumber;
  
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: numbers.length,
      itemBuilder: (context, index) {
        return ElevatedButton(
          child: Text('${numbers[index]}'),
          style: ElevatedButton.styleFrom(
            primary: numbers[index] == _selectedNumber 
                     ? Colors.green : Colors.white, // background
            onPrimary: numbers[index] == _selectedNumber 
                       ? Colors.white : Colors.green, // foreground
          ),
          onPressed: (){ 
            setState(() { _selectedNumber = numbers[index]; });
          },
        );
      },
    );
  }
}
answered on Stack Overflow Apr 16, 2021 by nvoigt

User contributions licensed under CC BY-SA 3.0