【问题标题】:Flutter State management with Provider using multiple screens使用多个屏幕使用 Provider 进行 Flutter 状态管理
【发布时间】:2023-03-14 10:39:01
【问题描述】:

我的应用中有两个页面,Page_APage_B。我有另外两个类在我的Privider Class 中更新_votes 变量(默认= 0),然后在Page_A 中显示这个变量,这可以正常工作。

我正在尝试访问这个变量 (_votes),它现在在新页面 Page_B 中更新为 23。但是,当新页面被推送到屏幕时,变量似乎被重置为0 而不是23。我怎样才能实现我想要做的事情。

【问题讨论】:

  • 你能展示一下你到目前为止做了什么吗?

标签: flutter dart provider


【解决方案1】:

假设这是您的提供程序类

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));
      }
   }

【讨论】:

  • 将“builder: () => AppState()”替换为“create: () => TodoProvider()”。 Builder 已在 Provider 库的最新版本中被弃用。
猜你喜欢
  • 1970-01-01
  • 2021-01-15
  • 2021-02-15
  • 2021-12-23
  • 1970-01-01
  • 2020-05-01
  • 2021-08-27
  • 2021-05-30
  • 2020-09-29
相关资源
最近更新 更多