【问题标题】:How do elegantly use variables for a state in Flutter/Dart?如何优雅地使用 Flutter/Dart 中的状态变量?
【发布时间】:2021-03-24 11:09:01
【问题描述】:
class EventCreator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget> [
          Positioned.fill(
            child: Image(
              image: AssetImage('images/planning.jpg'),
              fit: BoxFit.cover,
            ),
          ),
          Container(
            child: Column(
              children: <Widget>[

                //DropdownBehavior(valueArg, listArg), idea

                DropdownBehavior(), // current

              ],
            ),
          ),
        ],
      ),
    );
  }
}

class DropdownBehavior extends StatefulWidget {
  DropdownBehavior({Key key}) : super(key: key);
  @override
  _DropdownBehavior createState() => _DropdownBehavior();
}

class _DropdownBehavior extends 
  State<DropdownBehavior> {
  String dropdownValue = "Public event";
  List<String> dropdownlist = ['Public event', ['Private event'];
                                         // These should be variables,
  @override                              // and be modifiable in EventCreator

  Widget build(BuildContext context) {
    return DropdownButton<String>(
      value: dropdownValue,
      elevation: 16,
      style: TextStyle(color: Colors.white),
      dropdownColor: Colors.black,
      underline: Container(
        height: 2,
        color: Colors.deepPurpleAccent,
      ),
      onChanged: (String newValue) {
        setState(() {
          dropdownValue = newValue;
        });
      },
      items: dropdownlist.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
    );
  }

}

我有以下代码。我希望能够将我的类 DropdownBehavior 重新用于各种类型的值。因此,我相信我需要一个可以传递给 DropdownBehavior 构造函数的变量,从而每次更改类的工作方式。

我在DropdownBehavior中尝试了一些不同的构造函数实现,但似乎我对Flutter中的States了解不足,因为我无法理解它是如何工作的。我也不明白构造函数中“Key”的使用以及它是如何使用的。

我使用DropdownButton sample code 进行一般实现。

我是 Flutter 和应用程序开发的新手,所以我很想解释一下为什么我正在做的事情很愚蠢。

TL;DR:想要一个可用于下拉菜单的通用类,我可以在其中填写初始提示值的值和可供选择的整个值列表。

【问题讨论】:

    标签: android-studio flutter dart


    【解决方案1】:

    我可能认为您正在做的事情是合并状态管理和类创建的概念。这可能很好,或者分开考虑它们会更好。

    例如,就寻求帮助时要搜索的内容而言,我认为您在此处编写的任何内容都不一定与状态管理过度相关,而更多的是小部件构建。传递变量的起点是将变量放在 DropDownBehavior 类中(与 Key 一起使用)。我认为它更简单:与其创建有状态的小部件和状态,不如考虑尝试拥有一个接受参数并返回下拉按钮的函数。

    这是一个删节的例子:

    class MyHomePage extends StatefulWidget {
    MyHomePage({Key key, this.title}) : super(key: key);
      final String title;
    //Etc.
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title)
             )
           );
       }
    }
    
    
    

    【讨论】:

    • 太棒了。我尝试创建一个新的构造函数,但没有意识到我仍然需要它的“Key”部分,也没有意识到我可以在“Key”部分之后添加更多参数。现在我应该可以解决我的问题了。
    【解决方案2】:
    class DropdownBehavior extends StatefulWidget {
      DropdownBehavior({Key key, List<String> dropdownlist) : super(key: key); // added dropdownlist 
      final Function(String) selectedValue;
      @override
      _DropdownBehavior createState() => _DropdownBehavior();
    }
    
    class _DropdownBehavior extends 
      State<DropdownBehavior> {
      String dropdownValue = "Public event";
      List<String> dropdownlist = ['Public event', ['Private event']; 
                                             // These should be variables,
      @override                              // and be modifiable in EventCreator
    
      Widget build(BuildContext context) {
        return DropdownButton<String>(
          value: dropdownValue,
          elevation: 16,
          style: TextStyle(color: Colors.white),
          dropdownColor: Colors.black,
          underline: Container(
            height: 2,
            color: Colors.deepPurpleAccent,
          ),
          onChanged: (String newValue) {
            setState(() {
              widget.selectedValue(newValue); // added
              dropdownValue = newValue;
            });
          }, // added widget. below
          items: widget.dropdownlist.map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
        );
      }
    
    }
    

    然后在你的调用类中输入 `DropdownBehavior(dropdownlist: mydropdownlist, selectedValue: (String val) => setState(() => foo = val)

    这个神奇的关键词是回调函数

    【讨论】:

    • 也感谢您的解决方案。我选择了另一个答案作为官方答案,因为它在整体解释中更深入。但是,感谢您对我下次如何更好地识别此类问题的见解,现在我知道下次该谷歌什么了:)。
    • 再想一想,您能否详细说明最后一行 /(String val) => setState(() => foo = val)/ ?
    • 如果你用谷歌搜索它,你会发现它 ;-) 你调用 DropdownBehaviour,它将使用selectedValue 发送回调。您使用(Sting val) 选择它的值并将其分配给某个状态变量。所以 foo = val 是你想要对所选值做的任何事情
    • 非常感谢,终于想通了如何应用一切。从这个帖子中学到了很多东西!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 1970-01-01
    • 2017-02-18
    • 2019-07-25
    • 2020-02-29
    • 1970-01-01
    相关资源
    最近更新 更多