Thomas M
Thomas M

Reputation: 25

Toggle switch is resetting in Flutter

I am new to flutter. I am adding a toggle switch. Toggle switch is resetting each time after selecting the dropdown I used below the toggle switch. I have not used any model for the switch. But I am not sure why the toggle switch is resetting.

 NeuCard(
                    curveType: CurveType.flat,
                    bevel: 10,
                    margin: EdgeInsets.all(10),
                    padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
                    decoration: NeumorphicDecoration(
                      borderRadius: BorderRadius.circular(35),
                      color:Color(0xffecedf1) ,
                    ),
                    child:  Center(
                      child: ToggleSwitch(
                        minWidth: MediaQuery.of(context).size.width/2.5,
                        inactiveBgColor: Color(0xffecedf1) ,
                        activeBgColor: Colors.white,
                        activeFgColor: Colors.black87,
                        labels: genders,
                        onToggle: (index) {
                          selectedGender = genders[index];
                          print('switched to: $index');
                        },
                      ),
                    )
                ),

Upvotes: 1

Views: 950

Answers (1)

Phake
Phake

Reputation: 1349

The package you are using has an argument called initialLabelIndex. There, you can set where the switch "lays" on, every time it initializes.

Create an integer for storing the labelIndex before your build function:

int initialIndex = 0;
@override
Widget build(BuildContext context) { ... }

Then you set the initialLabelIndex to that value:

ToggleSwitch(
  minWidth: MediaQuery.of(context).size.width/2.5,
  initialLabelIndex = labelIndex,
  inactiveBgColor: Color(0xffecedf1) ,
  activeBgColor: Colors.white,
  activeFgColor: Colors.black87,
  labels: genders,
  onToggle: (index) {
    selectedGender = genders[index];
    print('switched to: $index');
    setState(() {
      initialIndex = index; // here you set the initialIndex to the current index.
    });
  },
),

Upvotes: 2

Related Questions