简体   繁体   中英

Runtime polymorphism by using Provider Package in Flutter

How to apply run-time polymorphism by using Provider Package in Flutter ? 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. I need to provide the Repository instance throughout the app.

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 . Thus need to provide and swap dependencies at runtime by using the 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()

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

  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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