拨动开关正在 Flutter 中重置

Toggle switch is resetting in Flutter

我是 Flutter 新手。 我正在添加一个拨动开关。选择我在拨动开关下方使用的下拉菜单后,每次都会重置拨动开关。 我没有使用任何型号的开关。 但是我不确定为什么拨动开关会重置。

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

您正在使用的包有一个名为 initialLabelIndex 的参数。在那里,您可以设置每次初始化时开关“打开”的位置。

在构建函数之前创建一个用于存储 labelIndex 的整数:

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

然后将 initialLabelIndex 设置为该值:

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