Flutter ToggleSwitch 不会改变颜色

Flutter ToggleSwitch doesn’t change color

我有一个 ToggleSwitch,它与 setState 一起工作很好,但只要我在它的 onToggle 中调用 setState,它的 activeBgColor 就不会再改变。无论哪个按钮处于切换状态,activeBgColor 始终处于首选状态,但 setState 值正在发生变化。

另外我想把它放在容器的水平中间,所以我把它排成一排,但它仍然粘在容器的开头

代码如下:

 class _MyPovPageState extends State<MyPovPage> {
  final userUID = FirebaseAuth.instance.currentUser!.uid;
  final database = FirebaseDatabase.instance.ref();
  final tm = TaskManager();
  final wmy = [Text('Week'), Text('Month'), Text('Year')];

  late final en;
  late final username;
  late final background;
  var myTask = [];
  var myDaily = [];
  var myHistory = [];
  var dailyTemp = [];
  var selectedIndex = 0;

  @override
  initState() {
    super.initState();
    initInfo();
  }

  initInfo() {
    database.child(userUID).onValue.listen((event) {
      final data = Map<dynamic, dynamic>.from(event.snapshot.value as Map);
      setState(() {
        username = data['username'];
        background = data['background'];
        final language = data['language'];
        en = language.toString().startsWith('en');

        if (data['myDaily'] != null) {
          final dailyMap = Map<dynamic, dynamic>.from(data['myDaily']);
          dailyMap.forEach((key, value) {
            myDaily.add(tm.fromJson(value));
            //myTask.add(tm.fromJson(value));
          });
        }

        if (data['myTask'] != null) {
          final taskMap = Map<dynamic, dynamic>.from(data['myTask']);
          taskMap.forEach((key, value) {
            myTask.add(tm.fromJson(value));
          });
        }

        if (data['history'] != null) {
          final historyMap = Map<dynamic, dynamic>.from(data['history']);
          historyMap.forEach((key, value) {
            myHistory.add(tm.fromJson(value));
          });
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
            constraints: const BoxConstraints.expand(),
            decoration: BoxDecoration(
                image: DecorationImage(
              image: NetworkImage(background),
              fit: BoxFit.cover,
            )),
            child: ListView(
              padding: const EdgeInsets.only(top: 90),
              children: [
                getHello(),
                const SizedBox(height: 25),
                getDailyTaskWidget(),
                const SizedBox(height: 12),
                getChartWidget(),
                const SizedBox(height: 25),
                getTaskHeading(),
                getTaskList(),
              ],
            )));
  }

  Widget getChartWidget() {
    return Padding(
      padding: const EdgeInsets.only(left: 24, right: 24),
      child: Container(
          decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(20))),
          child: Column(children: [
            Row(
              children: [
                const SizedBox(width: 14),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const SizedBox(height: 14),
                    Text(en ? 'Score Chart' : '积分图表',
                        style: const TextStyle(
                            fontSize: 15,
                            fontWeight: FontWeight.bold,
                            color: Colors.black,
                            decoration: TextDecoration.none)),
                    const SizedBox(height: 4),
                    Row(
                      children: [
                        const Text('-',
                            style: TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                                decoration: TextDecoration.none)),
                        Text(en ? 'Daily' : '日常任务',
                            style: const TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                                decoration: TextDecoration.none)),
                        const SizedBox(width: 14),
                        const Text('-',
                            style: TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                                decoration: TextDecoration.none)),
                        Text(en ? ' Wishes' : ' 愿望分',
                            style: const TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                                decoration: TextDecoration.none)),
                        const SizedBox(width: 14),
                        const Text('-',
                            style: TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                                decoration: TextDecoration.none)),
                        Text(en ? ' Surprises' : ' 惊喜分',
                            style: const TextStyle(
                                fontSize: 12,
                                color: Colors.black,
                                decoration: TextDecoration.none)),
                      ],
                    ),
                    const SizedBox(height: 14),
                  ],
                ),
              ],
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                wmy[selectedIndex],
                const SizedBox(height: 14),
                const SizedBox(height: 14),
                getBigToggle(),
                const SizedBox(height: 14),
              ],
            )
          ])),
    );
  }

  Widget getBigToggle() {
    return Row(mainAxisAlignment: MainAxisAlignment.center, children: [
      ToggleSwitch(
        totalSwitches: 3,
        minWidth: 100.0,
        minHeight: 16.0,
        fontSize: 12,
        cornerRadius: 20.0,
        activeBgColor: [
          Color.fromARGB(255, 218, 203, 246),
        ],
        activeFgColor: Colors.black,
        inactiveBgColor: Colors.white,
        inactiveFgColor: Colors.black,
        labels: [en ? 'Week' : '周', en ? 'Month' : '月', en ? 'Year' : '年'],
        onToggle: (index) {
          setState(() {
            selectedIndex = index!;
          });
        },
      )
    ]);
  }

将 selectedIndex 类型从 var 更改为 int

  int selectedIndex = 0;

或者 您可以指定 ToggleSwitch 的 initialLabelIndex 属性 并将 selectedIndex 传递给它。

  var selectedIndex = 0;

  ToggleSwitch(
    initialLabelIndex: selectedIndex,
    totalSwitches: 3,
    minWidth: 100.0,
    minHeight: 16.0,
    fontSize: 12,
    cornerRadius: 20.0,
    activeBgColor: [
      Color.fromARGB(215, 118, 203, 146),
      Color.fromARGB(123, 218, 203, 246),

    ],

    labels: [en ? 'Week' : '周', en ? 'Month' : '月', en ? 'Year' : '年'],
    onToggle: (index) {
      setState(() {
        selectedIndex = index!;
      });
    },
  )