Search code examples
flutter

I've created a Stateful class but I'm not sure were the setState command goes in order to reload the screen if I add button


I created a stateful widget and my understanding is I can use setState if I add for instance buttons to the class during execution. I am trying to add a button depending on what the user selects in a dropdown menu but never see the button on the screen. Can someone tell me where the setState goes to accomplish this? Thanks

 class Page2 extends StatefulWidget {
  const Page2({super.key});
  @override

  _Page2State createState() => _Page2State(); 


}

class _Page2State extends State<Page2> {

  Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData(
            textTheme: TextTheme(
                displayLarge: const TextStyle(
                    fontSize: 84, fontWeight: FontWeight.bold))),
        home: Scaffold(
            body: Center(
                child: Column(children: <Widget>[
          //body: Center(child:
          //body: Column(
          //mainAxisAlignment: MainAxisAlignment.start,
          //crossAxisAlignment: CrossAxisAlignment.start,
          //children: <Widget>[
          //ElevatedButton.icon(
          //  icon: const Icon(Icons.add, size: 18),
          //  label: Text('Create Session'),
          //  onPressed: () {
          //    debugPrint('Create Session Button Pressed');
          //  },
          //),
          //SizedBox(height: 30),
          //ElevatedButton.icon(
          //  icon: const Icon(Icons.add, size: 18),
          //  label: Text('Edit Session'),
          //  onPressed: () {
          //    debugPrint('Edit Session Button Pressed');
          //  },
          //),
          //SizedBox(height: 30),
          //ElevatedButton.icon(
          //  icon: const Icon(Icons.add, size: 18),
          //  label: Text('Delete Session'),
          //  onPressed: () {
          //    debugPrint('Delete Session Button Pressed');
          //  },
          //),
          //Divider(color:Colors.black),
          //Expanded(
          //Flexible(
          //    child: Row(children: <Widget>[
          SizedBox(height: 50),
          //children: [
          DropdownMenu(
              width: 200,
              textStyle: TextStyle(fontSize: 14),
              label: const Text('Session Options'),
              inputDecorationTheme: InputDecorationTheme(
                  isDense: true,
                  contentPadding: const EdgeInsets.symmetric(horizontal: 5),
                  constraints: BoxConstraints.tight(const Size.fromHeight(40)),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10),
                  )),
              onSelected: (value) {
                debugPrint(value);
                if (value == 'Create Session') {
                  Set<String> searchType = {'Interior'};
                  SegmentedButton(segments:<ButtonSegment<String>>[ButtonSegment<String>(
                    value:'Interior',label: Text('Interior')),], selected: searchType,);
                }
                setState(() {
                  
                });
              },
              dropdownMenuEntries: <DropdownMenuEntry<String>>[
                DropdownMenuEntry(
                    value: 'Create Session', label: 'Create Session'),
                DropdownMenuEntry(value: 'Edit Session', label: 'Edit Session'),
                DropdownMenuEntry(
                    value: 'Delete Session', label: 'Delete Session'),
              ]
            ),
          ]
        )
      )
    )
  );
  }
}

Solution

  • Your StatefulWidget needs a variable that represents the widget state. In the example below this is the String sessionState. Notice that the list of widgets items defined in build depends on sessionState. You could extend the switch expression to add further cases like 'Edit Session'.

    The variable sessionState is set in the onSelected callback of your DropDownMenu. The method setState() is called in order to rebuild your widget, after the widget state has changed. You can copy/paste the example below into a dartpad.

    import 'package:flutter/material.dart';
    
    class Page2 extends StatefulWidget {
      const Page2({super.key});
    
      @override
      _Page2State createState() => _Page2State();
    }
    
    class _Page2State extends State<Page2> {
      String sessionState =
          'none'; // The variable describing the state of the widget
    
      @override
      Widget build(BuildContext context) {
        final List<Widget> items = switch (sessionState) {
          'Create Session' => [
              SegmentedButton(
                segments: [
                  const ButtonSegment<String>(
                    value: 'Interior',
                    label: Text('Interior'),
                  ),
                ],
                selected: {'Interior'},
              ),
              IconButton(onPressed: null, icon: Icon(Icons.add_alarm)), 
              // Add further items here
            ],
          _ => [],
        };
    
        return MaterialApp(
          theme: ThemeData(
              textTheme: TextTheme(
                  displayLarge:
                      const TextStyle(fontSize: 84, fontWeight: FontWeight.bold))),
          home: Scaffold(
            body: Center(
              child: Column(
                children: <Widget>[
                  SizedBox(height: 50),
                  //children: [
                  DropdownMenu(
                    width: 200,
                    textStyle: TextStyle(fontSize: 14),
                    label: const Text('Session Options'),
                    inputDecorationTheme: InputDecorationTheme(
                        isDense: true,
                        contentPadding: const EdgeInsets.symmetric(horizontal: 5),
                        constraints:
                            BoxConstraints.tight(const Size.fromHeight(40)),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(10),
                        )),
                    onSelected: (value) {
                      debugPrint(value);
                      if (value != null) {
                        setState(() {
                          // Triggering a rebuild of your widget
                          sessionState = value; // Setting the state variable
                        });
                      }
                    },
                    dropdownMenuEntries: <DropdownMenuEntry<String>>[
                      DropdownMenuEntry(
                          value: 'Create Session', label: 'Create Session'),
                      DropdownMenuEntry(
                          value: 'Edit Session', label: 'Edit Session'),
                      DropdownMenuEntry(
                          value: 'Delete Session', label: 'Delete Session'),
                    ],
                  ),
                  ...items,
                ],
              ),
            ),
          ),
        );
      }
    }
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) => Page2();
    }