In this blog, we are going to learn about OneContext In Flutter. And check how we can use it in Flutter app development to reduce the code & maintain the context throughout the application.
Before starting the topic, we need to clarify what is BuildContext and why we use it to perform actions like navigation, showing alert dialog, and fetching the data from MediaQuery.
In Flutter, BuildContext is a locator that can be used to locate the widget in the widget tree. The BuildContext of each widget is passed to their build method and all widgets have unique BuildContext. We can say it is an instance of the Widget and it holds all the information related to it.
Before moving further, you can also check our Flutter app development company page.
We will follow the mentioned steps for integrating the OneContext In Flutter:
1. Adding Dependency
Firstly, we will add the updated flutter package of one_context in “pubspec. ymal” file.
1 2 3 4 5 6 7 8 9 |
dependencies: flutter: sdk: flutter # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 one_context: ^2.1.0 |
We have to add the updated version of the library, you can check the compatible version on Flutter pub.dev and use it accordingly.
2. Implementation
We can use OneContext in our code as per the need, there are multiple uses for it. For showing global dialogs, overlay alerts, changing the theme, navigation from one page to another, reloading & restarting the app etcetera.
In this blog, we will be going to perform some tasks with OneContext.
1. Showing Dialog
We don’t need BuildContext to show dialogs
1 2 3 4 5 6 |
OneContext().showDialog( builder: (_) => AlertDialog( title: new Text("Dialog"), content: new Text("Dialog with One Context"), ) ); |
we can use a similar code snippet with bottom sheet dialogs and modal bottom sheet dialogs
2. Navigation Using OneContext
1 2 3 4 5 |
OneContext().push(MaterialPageRoute(builder: (_) => LoginPage())); // for getting result from second screen to first screen String backResult = await OneContext().push<String>(MaterialPageRoute(builder: (_) => LoginPage())); print(backResult); |
3. Changing Theme
1 2 3 4 5 6 7 8 9 10 |
OneNotification<OneThemeChangerEvent>( builder: (_, __) { return MaterialApp( builder: OneContext().builder, themeMode: OneThemeController.initThemeMode(ThemeMode.light), theme: OneThemeController.initThemeData(ThemeData(brightness: Brightness.light)), darkTheme: OneThemeController.initDarkThemeData(ThemeData(brightness: Brightness.dark)), ... ); ); |
There are many uses where you can use OneContext instead of BuildContext as per your needs and requirements.
Conclusion:
In this blog, you have learned about the OneContext In Flutter.
You can also go through the official Flutter site to learn more about the same.