我的应用中有两个页面:Page_A
和 Page_B
。我还有另外两个类,它们在我的 Privider Class
中更新 _votes
变量(默认 = 0),然后在 Page_A
中显示此变量,效果很好正如所料。
我正在尝试访问此变量 (_votes
),该变量现已更新为新页面 Page_B
中的 23
。但是,当新页面推送到屏幕时,变量似乎会重置为 0
而不是 23
。我怎样才能实现我想要做的事情。
最佳答案
假设这是您的提供程序类
class AppState with ChangeNotifier {
int _votes = 0;
getVotes() => _votes;
setVotes(votes) {
_votes = votes;
notifyListeners();
}}
//访问
appState = Provider.of<AppState>(context);
//获取当前值
appState.getVotes();
//设置值
v = 23;
appState.setVotes(v);
确保根类应如下所示:
void main() {
runApp(new MyApp());}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<AppState>(
create: (_) => AppState(),
child: MaterialApp(
home: HomePage(),
debugShowCheckedModeBanner: false));
}
}
关于使用多个屏幕通过 Provider 进行 Flutter 状态管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58625713/