简体   繁体   English

选择某些内容时下拉菜单不更新(颤振)

[英]DropDown Menu isn't updating when something is selected(Flutter)

I am trying to create a DropDown menu in my Flutter project, but it's value doesn't change when I press on a value.我正在尝试在我的 Flutter 项目中创建一个下拉菜单,但是当我按下一个值时它的值不会改变。 I've tried several different codes and tutorials, but it never seems to change.我尝试了几种不同的代码和教程,但似乎从未改变。 Here is my code:这是我的代码:

    body: Container(
      padding: EdgeInsets.fromLTRB(10.0, 20.0, 10.0, 30.0),
      child: Column(
        children: <Widget>[
          TextField(
            controller: myController,
            decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Title',
                hintText: 'What will you call your grocery list?'),
          ),
          Row(
            children: <Widget>[
              Text(
                'Remind me every ',
                style: GoogleFonts.biryani(fontSize: 15.0),
              ),
              new DropdownButton<String>(
                value: 'Wednesday',
                items: <String>[
                  'Sunday',
                  'Monday',
                  'Tuesday',
                  'Wednesday',
                  'Thursday',
                  'Friday',
                  'Saturday'
                ].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (_) {},
              ),
            ],
          )
        ],
      ),
    )

Also, this code is inside of a class separate from the mainpage of the file, which is also a stateful widget.此外,此代码位于与文件主页分开的 class 内部,这也是一个有状态的小部件。 Basically, I'll end up with two stateful widgets, the main page, and this page, and it won't let me create two states.基本上,我最终会得到两个有状态的小部件,主页面和这个页面,它不会让我创建两个状态。 Here is the error it gives me:这是它给我的错误:

The name 'createState' is already defined.
Try renaming one of the declarations.dartduplicate_definition

You are hardcoding the value parameter inside the dropdown button so it'll never change.您正在对下拉按钮内的 value 参数进行硬编码,因此它永远不会改变。 You need to make a variable in the beginning of a stateful widget class and inititalize like this您需要在有状态小部件 class 的开头创建一个变量并像这样初始化

String value = "Wednesday";

Than you need to change its value onChanged function of the DropdownButton and call setState to update the Ui with new values.比您需要更改其值onChanged function 的 DropdownButton 并调用 setState 以使用新值更新 Ui。 This is how your stateful widget class would look like这就是您的有状态小部件 class 的样子

class _MyHomePageState extends State<MyHomePage> {
  String value = "Wednesday";
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
      padding: EdgeInsets.fromLTRB(10.0, 20.0, 10.0, 30.0),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              new DropdownButton<String>(
                value: value,
                items: <String>[
                  'Sunday',
                  'Monday',
                  'Tuesday',
                  'Wednesday',
                  'Thursday',
                  'Friday',
                  'Saturday'
                ].map((String value) {
                  return new DropdownMenuItem<String>(
                    value: value,
                    child: new Text(value),
                  );
                }).toList(),
                onChanged: (val) {
                  setState((){
                    this.value = val;
                  });
                },
              ),
            ],
          )
        ],
      )));
  }
}

You have to declare a variable outside of the DropdownButton and set the selected value to that.您必须在 DropdownButton 之外声明一个变量并将所选值设置为该变量。

Here is a sample这是一个示例

String _currentValue='Saturday';

 body: Container(
  padding: EdgeInsets.fromLTRB(10.0, 20.0, 10.0, 30.0),
  child: Column(
    children: <Widget>[
      TextField(
        controller: myController,
        decoration: InputDecoration(
            border: OutlineInputBorder(),
            labelText: 'Title',
            hintText: 'What will you call your grocery list?'),
      ),
      Row(
        children: <Widget>[
          Text(
            'Remind me every ',
            style: GoogleFonts.biryani(fontSize: 15.0),
          ),
          new DropdownButton<String>(
            value: _currentValue,
            items: <String>[
              'Sunday',
              'Monday',
              'Tuesday',
              'Wednesday',
              'Thursday',
              'Friday',
              'Saturday'
            ].map((String value) {
              return new DropdownMenuItem<String>(
                value: value,
                child: new Text(value),
              );
            }).toList(),
            onChanged: (_) {
              setState(() {
                  _selectedValue = _;
                });
            },
          ),
        ],
      )
    ],
  ),
)

UPDATE更新

----------------------- ----------------------

Just use two separate and different Stateful widget, one for the page and one for the selector, Check this dartpad to better understand how you can split your StatefulWidget into two separate StatefulWidgets只需使用两个独立且不同的 Stateful 小部件,一个用于页面,一个用于选择器,检查此 dartpad 以更好地了解如何将 StatefulWidget 拆分为两个单独的 StatefulWidget

https://dartpad.dev/b07af2a7d088caeb312e5fc0cf6c5f10 https://dartpad.dev/b07af2a7d088caeb312e5fc0cf6c5f10

----------------------- ----------------------

You have HardCoded you "Wednesday" value, you should put it in a variable and set it on the on changed method, of course all of this should be done inside a StatefulWidget because you are managing the state你已经硬编码了你的“星期三”值,你应该把它放在一个变量中并将它设置在 on changed 方法上,当然所有这些都应该在 StatefulWidget 内完成,因为你正在管理 state

Your stateful widget您的有状态小部件

class TestWidget extends StatefulWidget {
  @override
  _TestWidgetState createState() => _TestWidgetState();
}

Your State你的 State

class _TestWidgetState extends State<TestWidget> {

  //Your String used for defining the selection**
  String _currentSelection = "Wednesday";

  //Your build method    
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("DropDownSample"),
        ),
        body: Container(
          padding: EdgeInsets.fromLTRB(10.0, 20.0, 10.0, 30.0),
          child: Column(
            children: <Widget>[
              Row(
                children: <Widget>[
                  Text('Remind me every '),
                  DropdownButton<String>(
                    //Don't forget to pass your variable to the current value
                    value: _currentSelection,
                    items: <String>[
                      'Sunday',
                      'Monday',
                      'Tuesday',
                      'Wednesday',
                      'Thursday',
                      'Friday',
                      'Saturday'
                    ].map((String value) {
                      return new DropdownMenuItem<String>(
                        value: value,
                        child: new Text(value),
                      );
                    }).toList(),
                    //On changed update the variable name and don't forgot the set state!
                    onChanged: (newValue) {
                      setState(() {
                        _currentSelection = newValue;
                      });
                    },
                  ),
                ],
              )
            ],
          ),
        ));
  }
}

Check also why you should use the setState when updating a variable;) https://flutter.dev/docs/development/ui/interactive还要检查为什么在更新变量时应该使用 setState;) https://flutter.dev/docs/development/ui/interactive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM