如果我在另一个Dart文件中分离了一个小控件(PopupMenuButton) 我不能使用设置状态方法?
尽管PopupMenuButton是令人满意的小部件的子类 我不能使用setState吗?!
代码是:
PopupMenuButton<String> appBarMenu(BuildContext context, RateMyApp _rateMyApp) {
return PopupMenuButton<String>(
itemBuilder: (BuildContext context) {
return choicesMenuBtn.map((String choice) {
return PopupMenuItem<String>(
child: Text('RateUS'),
);
}).toList();
},
onSelected: (val) {
if (val == rateUsMenuBtn) {
_rateMyApp.showStarRateDialog(
context,
actionsBuilder: (_, count) {
final Widget cancelButton = RateMyAppNoButton(
_rateMyApp,
text: 'CANCEL',
//here is the problem
callback: () => setState(() {}),
);
},
);
}
});
}
答案 0 :(得分:1)
state和setState方法仅在扩展StatefullWidget类的类内可用,您的代码是返回小部件的函数(方法)。因此,方法setState
不可用。
一种解决方案是在您正在使用的statefullwidget中制作此方法
class Example extends StatefullWidet {
@override
createState() => _ExamleState();
}
class _ExampleState extends State<Example> {
PopupMenuButton<String> appBarMenu(BuildContext context, RateMyApp _rateMyApp) {
return PopupMenuButton<String>(
itemBuilder: (BuildContext context) {
return choicesMenuBtn.map((String choice) {
return PopupMenuItem<String>(
child: Text('RateUS'),
);
}).toList();
},
onSelected: (val) {
if (val == rateUsMenuBtn) {
_rateMyApp.showStarRateDialog(
context,
actionsBuilder: (_, count) {
final Widget cancelButton = RateMyAppNoButton(
_rateMyApp,
text: 'CANCEL',
//here is the problem
callback: () => setState(() {}),
);
},
);
}
});
}
// other code inside the widget
}
或
如果要在小部件中使用更多功能,可以将功能用作参数
PopupMenuButton<String> appBarMenu(BuildContext context, RateMyApp _rateMyApp, Function onPress) {
return PopupMenuButton<String>(
itemBuilder: (BuildContext context) {
return choicesMenuBtn.map((String choice) {
return PopupMenuItem<String>(
child: Text('RateUS'),
);
}).toList();
},
onSelected: (val) {
if (val == rateUsMenuBtn) {
_rateMyApp.showStarRateDialog(
context,
actionsBuilder: (_, count) {
final Widget cancelButton = RateMyAppNoButton(
_rateMyApp,
text: 'CANCEL',
//here is the problem
callback: onPress,
);
},
);
}
});
}
// and whenever you call it you pass the onClick to the method.