最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flutter - I've created a Stateful class but I'm not sure were the setState command goes in order to reload the s

programmeradmin5浏览0评论

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

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'),
              ]
            ),
          ]
        )
      )
    )
  );
  }
}
Share Improve this question edited Jan 20 at 12:55 Ravindra S. Patil 14.8k4 gold badges19 silver badges49 bronze badges asked Jan 20 at 12:44 ChrisChris 53 bronze badges 3
  • what's your requirement after dropdown value selection? and add ; after if statement close – Ravindra S. Patil Commented Jan 20 at 12:51
  • The value that you want to reflect changes for, should be set within the setState block. In your given code put if condition in setState – DroidFlutter Commented Jan 20 at 12:52
  • If the user selects a particular entry in a dropdown menu, i'd like to add some buttons to the screen they are on so I was adding the setstate right after the If condition where I created the button, Thanks – Chris Commented Jan 20 at 12:56
Add a comment  | 

1 Answer 1

Reset to default 0

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();
}


与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论