skip to Main Content

Switch widget will properly work with these. But if I uncomment that section, Switch widget will freeze.
I need to set Switch initial value based on arguments condition. How to do that?

class BookingPageState extends State<BookingPage> {
  bool reqPickup = false; 

  Widget build(BuildContext context) {
    /* priceData = ModalRoute.of(context)?.settings.arguments;
    if(priceData) setState(() {reqPickup = true; }); */

    return Switch.adaptive(
      value: reqPickup,
      onChanged:(bool value) {
        setState(() {reqPickup = value; });
      }
    )
  }
}                                

2

Answers


  1. The problem is how do you set the initial data of your switch because every time that you set a new state the build method executes again and set your variable with the screen args
    You can solve this using the initState method of your statefulwidget like this

    class BookingPageState extends State<BookingPage> {
          bool reqPickup = false; 
        
          @override
          void initState() {
            super.initState();
            WidgetsBinding.instance.addPostFrameCallback((_) {
              priceData = ModalRoute.of(context)?.settings.arguments;
              if (priceData != null && mounted)
                setState(() {
                  reqPickup = true;
              }); 
            });
          }
    
          Widget build(BuildContext context) {
            return Switch.adaptive(
              value: reqPickup,
              onChanged:(bool value) {
                setState(() {reqPickup = value; });
              }
            )
          }
        }                                
    
    Login or Signup to reply.
  2. Here you go. I believe this is what you want. It is the minimum viable code, under 30 lines. I hope it works. Feel free to provide acknowledgement in the comment below.

    class BookingPage extends StatelessWidget {
      const BookingPage({super.key});
      static bool reqPickup = false;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: SafeArea(
            child: StatefulBuilder(
              builder: (BuildContext ctx, void Function(void Function()) setState) {
                final Object? object = ModalRoute.of(context)?.settings.arguments;
                final bool priceData = (object ?? false) as bool;
                if (priceData) {
                  reqPickup = true;
                  setState(() {});
                } else {}
                return Switch.adaptive(
                  value: reqPickup,
                  onChanged: (bool value) {
                    reqPickup = value;
                    setState(() {});
                  },
                );
              },
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search