【问题标题】:How to access provider in model class如何在模型类中访问提供者
【发布时间】:2021-04-09 16:11:54
【问题描述】:

我有一个不是小部件的类,所以它没有任何上下文。那么有什么方法可以让我在这个模型类中使用 ChangeNotifier 访问 Class。

模型类

class MyRouteObserver extends RouteObserver<PageRoute<dynamic>> {
@override
  void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {

    
    Provider.of<MyCass>(context, listen: false).restore();  // How I can do this ? as I dont have context here

    super.didPop(route, previousRoute);
    if (previousRoute is PageRoute && route is PageRoute) {
      _sendScreenView(previousRoute);
    }
  }
}

我的班级


class MyClass with ChangeNotifier {

  void restore() {
    .. Some logic
  }
}

【问题讨论】:

    标签: flutter dart flutter-provider


    【解决方案1】:

    将上下文添加到您的课程中

    final BuildContext context;
    

    然后将其添加到构造函数中

    const MyRouteObserver(this.context);
    

    这样您就可以将构建上下文从您的小部件类传递给您的类

    【讨论】:

    • 不要拘泥于上下文。即使在同一个小部件中,它们也是不同的。您总是需要 current 上下文。
    猜你喜欢
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多