gpt4 book ai didi

android-studio - 在flutter上对PopupMenuButton返回值方法使用setState方法

转载 作者:行者123 更新时间:2023-12-03 04:50:06 26 4
gpt4 key购买 nike

如果我在另一个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(() {}),
);
},
);
}
});
}

最佳答案

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.

关于android-studio - 在flutter上对PopupMenuButton返回值方法使用setState方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61552879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com