首页 > 解决方案 > 如何优雅地使用 Flutter/Dart 中的状态变量?

问题描述

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 示例代码用于一般实现。

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

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

标签: android-studioflutterdart

解决方案


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

例如,我认为您在此处编写的任何内容都不一定与状态管理过度相关,至于在寻求帮助时要搜索什么,而更多的是小部件构建。传递变量的起点是将变量放在 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)
         )
       );
   }
}



推荐阅读