Search code examples
fluttertoggleswitch

Flutter ToggleSwitch doesn’t change color


I have a ToggleSwitch, it works fine with setState, but as long as I’m calling setState in its onToggle, it’s activeBgColor doesn’t change anymore. No matter which button is on toggle, the activeBgColor will always on the first choice, but the setState value is changing.

Plus I was trying to place it in the horizontal middle of the container, so I put it in a Row, but it still sticks at the beginning of the container

Here is the code:

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

Solution

  • Change selectedIndex type from var to int

      int selectedIndex = 0;
    

    Or You can specify initialLabelIndex property of ToggleSwitch and pass selectedIndex to it.

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