无法在小部件中找到方法 'SetState'
Cannot Find Method 'SetState' within widget
我有一个稍后在我的主脚手架文件中调用的小部件。这个小部件包含一个下拉菜单,但是,我无法在选择另一个值时更改状态。该字段未更新,我收到错误消息“错误:未找到方法:'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(),
),
我需要能够更新值并在选择新值时显示它。
SetState 在 main 方法内部不可访问,在函数内部也不可访问,要使其可访问,您需要创建一个 Stateful class 并且恰好在 State class 中,因为实际上您的小部件是一个有状态的class:每次用户发生事件时它都会改变它的状态..
您不能在 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(),
);
}
}
我有一个稍后在我的主脚手架文件中调用的小部件。这个小部件包含一个下拉菜单,但是,我无法在选择另一个值时更改状态。该字段未更新,我收到错误消息“错误:未找到方法:'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(),
),
我需要能够更新值并在选择新值时显示它。
SetState 在 main 方法内部不可访问,在函数内部也不可访问,要使其可访问,您需要创建一个 Stateful class 并且恰好在 State class 中,因为实际上您的小部件是一个有状态的class:每次用户发生事件时它都会改变它的状态..
您不能在 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(),
);
}
}