Having issues updating the size of a widget with setState

Viewed 139

I am trying to learn how state works, and as an example am trying to get the width of a switch to change and re render when I choose between three options, small, medium and large. Everything was working until I added setState to update the build when I change the switchWidth. Is it possible to have the widget width update using state?

enter image description here

import 'package:fswitch/fswitch.dart';
import 'package:flutter/material.dart';
import 'package:toggle_switch/toggle_switch.dart';

class SwitchScreen extends StatefulWidget {

  @override
  _SwitchScreenState createState() => _SwitchScreenState();
}

class _SwitchScreenState extends State<SwitchScreen> {

  @override
  Widget build(BuildContext context) {

    double switchWidth;

    return Container(
      child: Stack(
        children:[
          Align(
            alignment: FractionalOffset.center,
            child: FSwitch(
              //HERE IS THE WIDTH
              width: switchWidth,
              height: 40,
              onChanged: (v) {
                //Play Sound
              },
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Padding(
              padding: const EdgeInsets.only(bottom: 100.0),
              child: ToggleSwitch(
                minWidth: 90.0,
                cornerRadius: 20.0,
                activeBgColor: Colors.lightBlue,
                activeFgColor: Colors.white,
                inactiveBgColor: Colors.grey,
                inactiveFgColor: Colors.white,
                labels: ['Small', 'Medium', "Long"],
                onToggle: (index) {
                
                //THIS IS CAUSING THE ISSUE
                  if(index == 0){
                    setState((){
                      switchWidth = 100;
                    });
                    print("small");
                  }
                  else if(index == 1){
                    setState((){
                      switchWidth = 200;
                    });
                    print("medium");
                  }
                  else if(index == 2){
                    setState((){
                      switchWidth = 300;
                    });
                    print("long");
                  }
                },
              ),
            ),
          ),
        ]
      ),
    );
  }
}
1 Answers

You have your switchWidth defined in your build method. When you call setState, it will reinitialize to null and reset its width. Define it in your state class:

class _SwitchScreenState extends State<SwitchScreen> {
  double switchWidth;
@override
Widget build(BuildContext) {
//Rest of code
}
Related