【问题标题】:Cannot Find Method 'SetState' within widget在小部件中找不到方法“SetState”
【发布时间】:2019-04-23 11:29:59
【问题描述】:

我有一个稍后在我的主脚手架文件中调用的小部件。此窗口小部件包含一个下拉菜单,但是,选择另一个值时,我无法更改状态。该字段未更新,我收到错误消息“错误:找不到方法:'setState'。 设置状态((){' ^^^^^^^^

我已经更新了 setState 方法并从中删除了代码,但它仍然说找不到该方法。

child: DropdownButton(
                  hint: Text('Medical'),
                  value: _selectedCustomerType,
                  onChanged: (newValue) {
                    setState(() {
                      _selectedCustomerType = newValue;
                    });
                  },
                  items: _customerType.map((cusType) {
                    print(cusType);

                    return DropdownMenuItem(
                      child: Text(cusType),
                      value: cusType,
                    );
                  }).toList(),
                ),

我需要能够更新值并在选择新值时显示它。

【问题讨论】:

  • 添加您的完整代码

标签: drop-down-menu flutter dropdown setstate


【解决方案1】:

您不能在 StatefulWidget 之外使用 setState,因此您应该将 DropdownButton 包装在 StatefulWidget 中,例如:

class StatefulDropdownButton extends StatefulWidget {
  final List<String> _customerType;

  StatefulDropdownButton(this._customerType);

  @override
  State<StatefulWidget> createState() => DropdownButtonState();
}

class DropdownButtonState extends State<StatefulDropdownButton> {
  String _selectedCustomerType;

  @override
  Widget build(BuildContext context) {
    return DropdownButton(
      hint: Text('Medical'),
      value: _selectedCustomerType,
      onChanged: (newValue) {
        setState(() {
          _selectedCustomerType = newValue;
        });
      },
      items: widget._customerType.map((cusType) {
        print(cusType);

        return DropdownMenuItem(
          child: Text(cusType),
          value: cusType,
        );
      }).toList(),
    );
  }
}

【讨论】:

  • 我刚试了一下,效果很好。我尝试在 Stateful 小部件之外使用设置状态。
【解决方案2】:

SetState 在 main 方法和函数内部都不可访问,要使其可访问,您需要在 State 类中创建一个有状态的类,因为实际上您的小部件是一个有状态的类:它每次都会更改其状态用户发起一个事件..

【讨论】:

  • 我无法捕获课程。这是一个被主小部件调用的小部件。
  • SetState 在 main 方法内是不可访问的,在函数内也不能访问,要使其可访问,您需要创建一个有状态的类,并且完全在 State 类中,因为实际上您的小部件是一个有状态的类:每次用户进行事件时,它都会更改其状态..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2021-05-01
  • 2020-08-18
  • 1970-01-01
  • 2019-10-01
  • 2021-03-08
相关资源
最近更新 更多