简体   繁体   English

在 Flutter 中使用 Provider Package 的运行时多态性

[英]Runtime polymorphism by using Provider Package in Flutter

How to apply run-time polymorphism by using Provider Package in Flutter ?如何通过在Flutter中使用Provider Package 来应用运行时多态性? I have an advanced use case.我有一个高级用例。 My app has a 'View Demo' button that brings the user into the app and he can view all the screens with some dummy data.我的应用程序有一个“查看演示”按钮,可将用户带入应用程序,他可以查看所有带有一些虚拟数据的屏幕。 This helps the user to view the whole app even before creating an account.这有助于用户在创建帐户之前查看整个应用程序。

I'm using the repository pattern and have a Repo abstract class and implemented by FirebaseRepo with actual data and MockRepo with dummy data.我正在使用存储库模式并有一个 Repo 抽象 class 并由FirebaseRepo用实际数据和MockRepo用虚拟数据实现。 I need to provide the Repository instance throughout the app.我需要在整个应用程序中提供 Repository 实例。

When the user clicks the login button, the Repository should be swapped with FirebaseRepo and when the user clicks the 'View Demo' button, the Repository instance should swap with the MockRepo .当用户单击登录按钮时,Repository 应与FirebaseRepo交换,当用户单击“查看演示”按钮时,Repository 实例应与MockRepo交换。 Thus need to provide and swap dependencies at runtime by using the Provider package.因此需要使用Provider package 在运行时提供和交换依赖项。 How to accomplish this?如何做到这一点?

Though out the app, I should be able to access the repository by simply using Provider.of<Repository>(context) rather than, Provider.of<RepositoryModel>(context).getRepository() so that I can simply do, Provider.of<Repository>(context).getUser()虽然在应用程序之外,我应该能够通过简单地使用Provider.of<Repository>(context)而不是Provider.of<RepositoryModel>(context).getRepository()来访问存储库,这样我就可以简单地使用Provider.of<Repository>(context).getUser()

Please try simple solution below.请尝试以下简单的解决方案。

abstract class Repository {}

class FirebaseRepo extends Repository {}

class MockRepo extends Repository {}
// on login
Provider<FirebaseRepo>(
  create: (_) => FirebaseRepo(),
  dispose: (_, bloc) => bloc.dispose(),
  child: MainPage<FirebaseRepo>(),
)

// on mock
Provider<MockRepo>(
  create: (_) => MockRepo(),
  dispose: (_, bloc) => bloc.dispose(),
  child: MainPage<MockRepo>(),
)
class MainPage<T extends Repository> extends StatefullWidget {
  _MainPageState createState() => _MainPageState<T extends Repository>();
}
class _MainPageState<T extends Repository> extends State<MainPage> {
  /// BLoC of type T.
  T bloc;

  @override
  void initState() {
    super.initState();
    bloc = Provider.of<T>(context, listen: false);
  }

  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM