【问题标题】:Flutter/Dart: Passing this.variable as parameterFlutter/Dart:将 this.variable 作为参数传递
【发布时间】:2020-09-09 13:45:48
【问题描述】:

我有一个我想使用单个小部件创建的配置文件字段列表,但我是 Flutter 的新手,似乎无法解决一件事:通过参数传递变量。我已经能够使用this.variable = value 创建许多工作正常的小部件,但现在我正试图将其转换为单个小部件以免重复自己,这就是我遇到问题的地方。

我有以下代码(当然删除了所有我认为不必要的代码)。这里目前显示错误The setter 'listType' isn't defined for the class '_ProfileDataState'.

class _ProfileDataState extends State<ProfileData> {
  final _countries = DropDownLists.countries;
  String _country;
  var listType; //<-- added this per comments

  Widget profileDropDown(var list, var listType) {
    return Card(
      onTap: () async {
        AlertDialog(
          content: DropdownButtonFormField<String>(
            isExpanded: true,
            items: list.map((String value) {
              return DropdownMenuItem<String>(
                value: value,
                child: Text(value),
              );
            }).toList(),
            isDense: true,
            value: listType,
            onChanged: (value) {
              FocusScope.of(context).requestFocus(FocusNode());
                setState(() {
                  this.listType = value;
                });
              },
          )
        )
      }
    )
  }

  @override
    Widget build(BuildContext context) {
      return profileDropDown(_countries, _country),
...

【问题讨论】:

    标签: function class flutter variables dart


    【解决方案1】:
    class _ProfileDataState extends State<ProfileData> {
      String _country;
      var listType; // declare a variable
    
      @override
      void initState() {
        super.initState();
        listType = widget.listType; // assign it a value here
      }
    
      Widget profileDropDown(var listType) {
        return Card(
            onTap: () async {
              AlertDialog(
                onChanged: (value) {
                  FocusScope.of(context).requestFocus(FocusNode());
                  setState(() {
                    this.listType = value; // works
                  });
                },
              )
            }
        )
      }
    
      // other methods
    }
    

    【讨论】:

    • 谢谢。我试过了,listType = widget.listType; 现在给我一个错误,说 getter 已定义。我尝试只在顶部包含空变量而没有初始化状态,但我得到了一个不同的错误,可能与另一个变量有关,它是一个列表。我刚刚在这里更新了我的代码以显示我遇到新问题的位置,即Unhandled Exception: type 'List&lt;dynamic&gt;' is not a subtype of type 'List&lt;DropdownMenuItem&lt;String&gt;&gt;'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2022-01-05
    • 2022-01-21
    • 2017-09-06
    • 2020-12-01
    • 1970-01-01
    相关资源
    最近更新 更多