Code Monkey home page Code Monkey logo

emanuel-braz / one_context Goto Github PK

View Code? Open in Web Editor NEW
73.0 3.0 21.0 188 KB

pub: https://pub.dev/packages/one_context - OneContext provides a simple way to deal with Dialogs, Overlays and Navigations with no need of BuildContext.

License: BSD 3-Clause "New" or "Revised" License

Kotlin 0.13% Swift 0.43% Objective-C 0.04% Dart 66.46% Ruby 1.43% Makefile 0.07% CMake 10.58% C++ 20.08% C 0.78%
context dart flutter flutter-package without-context dialogs

one_context's Introduction

Fork   Star   Watches

Pub Version PRs Welcome

logo

One Context to rule them all

OneContext provides a simple way to deal with Dialogs, Overlays, Navigations, Theme* and MediaQuery* with no need of BuildContext.

If you are Flutter developer, you don’t have to learn something new. This package use the same identificators and names from framework. It’s not a specialized* implementation, so you have the power to create and do not get blocked because of that.

If you are Flutter package developer, OneContext can be very useful too! You can create a custom dialogs package with no need BuildContext, and release a version, that do not depends of the context, to the comunity.

one_context_demo

BuildContext always is needed (in some cases we need to choose carefully the specific one to make things work as expected), but, to global things, like dialogs, it can be reached by OneContext package. 🎯

🎮 Let's start

⚠ Important: Configure MaterialApp. e.g.

/// important: Use [OneContext().builder] in `MaterialApp` builder, in order to show dialogs and overlays.
/// important: Use [OneContext().key] in `MaterialApp` navigatorKey, in order to navigate.
return MaterialApp(
    builder: OneContext().builder,
    navigatorKey: OneContext().key,
    ...
);

There are 2 ways to get OneContext singleton instance, OneContext() or OnceContext.intance. e.g.

    OneContext().pushNamed('/detail_page');
    OneContext.instance.pushNamed('/detail_page');

There are controllers to use navigation, overlays and dialogs. e.g.

    OneContext().navigator.pushNamed(...);
    OneContext().dialog.showDialog(...);
    OneContext().overlay.addOverlay(...);

Or, you can use the shortcuts ;)

    OneContext().pushNamed(...);
    OneContext().showDialog(...);
    OneContext().addOverlay(...);
    
    // and can access info from:
    // OneContext().mediaQuery ...
    // OneContext().textTheme ...
    // OneContext().theme ...

OneContext is:

  • Fast (O(1))
  • Easy to learn/use
  • It use same native function names from Flutter, to keep it simple and intuitive ;)

💬 How to show Dialogs with no need of the BuildContext?

// example snackBar
OneContext().showSnackBar(
    builder: (_) => SnackBar(content: Text('My awesome snackBar!'))
);
// example dialog
OneContext().showDialog(
    // barrierDismissible: false,
    builder: (_) => AlertDialog( 
        title: new Text("The Title"),
        content: new Text("The Body"),
    )
);
// example bottomSheet
OneContext().showBottomSheet(
    builder: (context) => Container(
    alignment: Alignment.topCenter,
    height: 200,
    child: IconButton(
        icon: Icon(Icons.arrow_drop_down),
        iconSize: 50,
        color: Colors.white,
        onPressed: () => Navigator.of(context).pop('sucess')), // or OneContext().popDialog('sucess');
    ),
);
// example modalBottomSheet
OneContext().showModalBottomSheet<String>(
    builder: (context) => Container(
        child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
            ListTile(
                leading: Icon(Icons.music_note),
                title: Text('Music'),
                onTap: () => OneContext().popDialog('Music'); //Navigator.of(context).pop('Music')),
            ListTile(
                leading: Icon(Icons.videocam),
                title: Text('Video'),
                onTap: () => Navigator.of(context).pop('Video'),
            ),
            SizedBox(height: 45)
            ],
        ),
    )
);

⛵ How to navigate? (All methods from Navigator Class are available)

// go to second page using named route
OneContext().pushNamed('/second');
// go to second page using MaterialPageRoute
OneContext().push(MaterialPageRoute(builder: (_) => SecondPage()));
// go back from second page
OneContext().pop();
// Pop dialogs
OneContext().popDialog();
// Retrieve data from route when it's pops
String result = await OneContext().push<String>(MaterialPageRoute(builder: (_) => SecondPage()));
print(result);

🍰 How to show Overlays?

// show the default progress indicator
OneContext().showProgressIndicator();
// hide the default progress indicator
OneContext().hideProgressIndicator();
// show the default progress indicator with some colors
OneContext().showProgressIndicator(
    backgroundColor: Colors.blue.withOpacity(.3),
    circularProgressIndicatorColor: Colors.white
);

// Later
OneContext().hideProgressIndicator();
// Show a custom progress indicator
OneContext().showProgressIndicator(
    builder: (_) => MyAwesomeProgressIndicator();
);

// Later
OneContext().hideProgressIndicator();
// Show a custom widget in overlay stack

String myCustomAndAwesomeOverlayId = UniqueKey().toString();

OneContext().addOverlay(
    overlayId: myCustomAndAwesomeOverlayId,
    builder: (_) => MyCustomAndAwesomeOverlay()
);

// Later
OneContext().removeOverlay(myCustomAndAwesomeOverlayId);

🎨 Changing Dark and Light theme mode

Breaking change: OneHotReload becomes OneNotification

⚠ Please check consideration on Theme and MediaQuery topic

OneNotification<OneThemeChangerEvent>(
  stopBubbling: true, // avoid bubbling to ancestors
  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)),
      ...
    );
);

// Later...
OneContext().oneTheme.toggleMode();

// Or change only the dark theme
OneContext().oneTheme.changeDarkThemeData(
  ThemeData(
    primarySwatch: Colors.amber,
    brightness: Brightness.dark
 )
);

🚧 Reload, Restart and Reboot the app (Need bubbling events or data?)

First define the data type in type generics, after that, you can rebuild multiple ancestors widgets that listen the same data type. This is used for the package in this example, to change ThemeMode and Locale and even Restart the app entirely.

OneNotification<List<Locale>>(
      onVisited: (context, localeList) {
        print('widget visited!');
      },
      stopBubbling: true, // avoid the data bubbling to ancestors widgets
      initialData: _localeEnglish, // [data] is null during boot of the application, but you can set initialData
      rebuildOnNull: true, // Allow other entities reload this widget without messing up currenty data (Data is cached on first event)
      builder: (context, localeList) {
        return MaterialApp(
          supportedLocales: localeList,
        );
      },
    );

Need to dispatch more specialized data/event?

// My Specialized Event
class MySpecializedEvent {
  final String text;
  MySpecializedEvent(this.text);
}

// Widget
OneNotification<MySpecializedEvent>(
  builder: (context, event) {
    return Text(event.text);
  },
)

// Later, in children, call `OneNotifier.notify` to get ancestors notified
OneNotifier.notify(
  context,
  NotificationPayload(
    data: MySpecializedEvent('Nice!');
  )
);

Reload and Restart the app

// Place that widget on most top
OneNotification(
  builder: (_, __) => child
);

// Later... in children

// Dont lose state
OneNotification.softReloadRoot(context);

// Lose state
OneNotification.hardReloadRoot(context);

Reboot and load different apps

// Set the main() function
void main() => OnePlatform.app = () => MyApp();

// Later... Call reboot without recreating root app
OnePlatform.reboot();

// Later... Call reboot recreating the entire application
OnePlatform.reboot(
  builder: () => MyApp()
);

// You even can load an entire different app
OnePlatform.reboot(
  builder: () => MyApp2()
);

⚙ Theme and MediaQuery

print('Platform: ' + OneContext().theme.platform); // TargetPlatform.iOS
print('Orientation: ' + OneContext().mediaQuery.orientation); // Orientation.portrait

[IMPORTANT] If you need get widget rebuild on theme data changes using OneContext().oneTheme.toggleMode();, please consider to use the traditional way Theme.of(context) when getting theme data inside widget.

@override
  Widget build(BuildContext context) {

    return Container(
      color: Theme.of(context).primaryColor, // Theme.of(context)
      height: 100,
      width: 100,
    );
  }

Or you can call Theme.of(context); in the begining of build method instead;

e.g.

@override
  Widget build(BuildContext context) {
    
    // Get changes by you currently context, and ensure the rebuild on theme data changes on
    // OneContext().oneTheme.toggleMode(), OneContext().oneTheme.changeDarkThemeData() or OneContext().oneTheme.changeThemeData() events.
    Theme.of(context);

    return Container(
      color: OneContext().theme.primaryColor, // OneContext().theme
      height: 100,
      width: 100,
    );
  }

In initState or inside class constructor (now it's possible)

@override
  void initState() {
    super.initState();

    OneContext().showDialog(
        builder: (_) => AlertDialog(
          title: new Text("On Page Load"),
          content: new Text("Hello World!"),
        ),
      );

🚦 Warnings

* OneContext().theme and OneContext().mediaQuery are global instances of the root of the widget tree. Use it with care! It can reproduce unexpected behavior if you don't understand it.

* OneContext().context is like a root context, so, it should not be used directly, as it can reproduce unexpected behaviors, unless you have a understanding how it works. It shouldn't work well with InheritedWidget for example.

* This package only uses specialized implementation in Overlays, to make things easy and ensure a quick start.

👨‍💻👨‍💻 Contributing

Contributions of any kind are welcome! I'll be glad to analyse and accept them! 👾

Sponsor

Buy Me A Coffee

one_context's People

Contributors

emanuel-braz avatar gumbarros avatar lijianqiang12 avatar ngatiajim avatar selvam920 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

one_context's Issues

Cannot hide or remove snackbar displayed by OneContext().showSnackBar

I want snackbars to disappear if the user clicks anywhere on them, but am unable to make it work with OneContext.

OneContext().showSnackBar(
    builder: (context) => SnackBar(
      content: GestureDetector(
        onTap: () {
          ScaffoldMessenger.of(context!).removeCurrentSnackBar(); //hideCurrentSnackBar also fails
        },
        child: Container(/* snip */),
    ),
  );

Is there another context object I should use? Or is there some other workaround to enable this?

show dialog without transition

how to show dialog or push page without transition animation.

Below are flutter code
showGeneralDialog(
context: context,
barrierDismissible: true,
barrierLabel: 'Text',
// barrierColor: Colors.white.withOpacity(0.9),
transitionDuration: const Duration(milliseconds: 0),
transitionBuilder: (context, animation, secondaryAnimation, child) {
return child;
},
pageBuilder: (BuildContext buildContext, Animation animation,
Animation secondaryAnimation) =>
Material(
type: MaterialType.transparency,
child: Align(
alignment: Alignment.center,
child: Container(
constraints: BoxConstraints(
maxWidth: maxWidth,
),
height: MediaQuery.of(context).size.height * height,
margin: const EdgeInsets.symmetric(vertical: 10),
child: child,
))))

Can we control the runApp function in OnePlatform when needed?

static Widget _app;
static set app(OnePlatformBuilder builder) => reboot(builder: builder);

 static void reboot({OnePlatformBuilder builder, VoidCallback setUp}) {
    setUp?.call();
    // ignore: unused_local_variable
    Widget oldWidget = _app;
    Future.delayed(Duration.zero, () {
      Widget newWidget = builder?.call();
      runApp(_app = newWidget ??
          OneBasicWidget(
            key: UniqueKey(),
            child: _app,
          ));
      oldWidget = null;
    });
  }

Already a builder in MaterialApp

Hello,

I'm trying to use your package, but it needs the builder of MaterialApp set to builder: OneContext().builder and I already have a custom builder set in my app. Is there a workaround for this?

Provider.of<T>(OneContext().context) has error

Error: Could not find the correct Provider above this Builder Widget
This likely happens because you used a BuildContext that does not include the provider
of your choice. There are a few common scenarios:

  • The provider you are trying to read is in a different route.
    Providers are "scoped". So if you insert of provider inside a route, then
    other routes will not be able to access that provider.
  • You used a BuildContext that is an ancestor of the provider you are trying to read.
    Make sure that Builder is under your MultiProvider/Provider.
    This usually happens when you are creating a provider and trying to read it immediately.

Not compatible with flutter 3.19

We need update I tried to build with latest flutter I'm getting the following error :
(Note: I have tried both Latest and Prerelease version)

my environment:
sdk: ">=2.14.4 <3.0.0"

JDK : 17.0.10
Kotlin : 1.9.22
gradle : 8.6
com.android.application : 8.2.2**

`../../AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/one_context-2.1.0/lib/src/controllers/one_context.dart:92:5: Error: Expected 0 type arguments.
    PersistentBottomSheetController<T> Function<T>({
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/one_context-2.1.0/lib/src/components/one_context_widget.dart:112:3: Error: Expected 0 type arguments.
  PersistentBottomSheetController<T> _showBottomSheet<T>({
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/one_context-2.1.0/lib/src/controllers/dialog_controller.mixin.dart:70:3: Error: Expected 0 type arguments.
  PersistentBottomSheetController<T> Function<T>({
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/one_context-2.1.0/lib/src/controllers/dialog_controller.mixin.dart:189:10: Error: Expected 0 type arguments.
  Future<PersistentBottomSheetController<T>?> showBottomSheet<T>({
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/one_context-2.1.0/lib/src/controllers/dialog_controller.mixin.dart:245:7: Error: Expected 0 type arguments.
      PersistentBottomSheetController<T> Function<T>({
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../AppData/Local/Pub/Cache/hosted/pub.flutter-io.cn/one_context-2.1.0/lib/src/components/one_context_widget.dart:122:12: Error: Expected 0 type arguments.
    return showBottomSheet<T>(
           ^
../../flutter/packages/flutter/lib/src/material/bottom_sheet.dart:1327:33: Context: Found this candidate, but the arguments don't match.
PersistentBottomSheetController showBottomSheet({
                                ^^^^^^^^^^^^^^^
Target kernel_snapshot failed: Exception


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\Users\zakbl\flutter\bin\flutter.bat'' finished with non-zero exit value 1
`

flutter 3.0

please update back_button_interceptor to version 6 for flutter 3.0

/C:/flutter/.pub-cache/hosted/pub.dartlang.org/back_button_interceptor-5.0.2/lib/src/back_button_interceptor.dart:29:74: Warning: Operand of null-aware operation '!' has type 'WidgetsBinding' which excludes null.
 - 'WidgetsBinding' is from 'package:flutter/src/widgets/binding.dart' ('/C:/flutter/packages/flutter/lib/src/widgets/binding.dart').
  static Future<void> Function() handlePopRouteFunction = WidgetsBinding.instance!.handlePopRoute;
                                                                         ^

When you will release the updated version!

Some latest features are missing please update package.

For example showDragHandle is available in latest version of flutter. and also some other features also

showModalBottomSheet( showDragHandle: true, context: context, builder: (context) { return Container( padding: const EdgeInsets.all(16.0), child: ListView.builder( itemCount: _ingredientList.length, itemBuilder: (context, index) { final ingredient = _ingredientList[index]; return ListTile( title: Text(ingredient), onTap: () { completer.complete(ingredient); Navigator.pop(context); // Close the bottom sheet after selecting an ingredient }, ); }, ), ); }, );

Issue on pop

Hello I have an issue when using pop in showDialog. When displaying showDialog using OneContext, it can run normally when performing actions with the OneContext().pop() function does not work as intended.

OneContext.instance.showDialog(
              builder: (context) => AlertDialog(
                title: const Text('Alert Dialog'),
                content: const Text('This is an alert dialog'),
                actions: [
                  TextButton(
                    onPressed: () {
                      OneContext().pop();
                    },
                    child: const Text('OK'),
                  ),
                ],
              ),
            );

Flutter 2.0.1 compatibility

Got this build error message in one of my apps: "since your app depends on both one_context ^0.5.0 and shared_preferences ^2.0.3, version solving failed". Using older versions of shared_preferences will also result in a "version solving problem" with the other packages.

Hero not working

Flutter 3.7.0
one_context: ^4.0.0

Using just a basic Hero doesn't work when navigating to sites i.e.
Navigator.pushNamed(context, CheckoutScreen.routeName);
or
OneContext().pushNamed(CheckoutScreen.routeName);

If I remove this from my material app, then Hero animation works again suddenly, do you know a solution ?
And confirms the Hero bug is due to OneContext

MaterialApp(
navigatorKey: OneContext().key,
builder: OneContext().builder, --> remove this

SnackBar covered by keyboard

Once the OneContext().builder set up, this case will recurring

without builder and key , the SnackBar running well.

OneContext not initiated! please use builder method

Hi, I loved your package and especially it solved the basic problem of passing build context everywhere. So basically I wanted to show the snackbar very easily but couldn't able to, due to flutters limitations. Well I've used your package and I must say I'm very much happy with but I'm getting one error on the start of the application which is this:

E/flutter ( 7896): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: 'package:one_context/src/controllers/one_context.dart': Failed assertion: line 17 pos 9: '_context != null': OneContext not initiated! please use builder method. E/flutter ( 7896): E/flutter ( 7896): You need to use the OneContext().builder function to be able to show dialogs and overlays! e.g. -> E/flutter ( 7896): E/flutter ( 7896): MaterialApp( E/flutter ( 7896): builder: OneContext().builder, E/flutter ( 7896): ... E/flutter ( 7896): ) E/flutter ( 7896): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39) E/flutter ( 7896): #1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5) E/flutter ( 7896): #2 OneContext.context (package:one_context/src/controllers/one_context.dart:17:9) E/flutter ( 7896): #3 OneThemeController.loadThemeMode (package:one_context/src/controllers/one_theme_controller.dart:80:50) E/flutter ( 7896): <asynchronous suspension> E/flutter ( 7896): #4 new OneThemeController (package:one_context/src/controllers/one_theme_controller.dart:26:5) E/flutter ( 7896): #5 new OneContext._private (package:one_context/src/controllers/one_context.dart:49:16) E/flutter ( 7896): #6 OneContext.instance (package:one_context/src/controllers/one_context.dart:52:43) E/flutter ( 7896): #7 OneContext.instance (package:one_context/src/controllers/one_context.dart) E/flutter ( 7896): #8 new OneContext (package:one_context/src/controllers/one_context.dart:53:27) E/flutter ( 7896): #9 WlcmClubApp.navKey (package:wlcmclub/app.dart:33:7) E/flutter ( 7896): #10 WlcmClubApp.navKey (package:wlcmclub/app.dart) E/flutter ( 7896): #11 _WlcmClubAppState.build (package:wlcmclub/app.dart:72:37) E/flutter ( 7896): #12 StatefulElement.build (package:flutter/src/widgets/framework.dart:4663:28) E/flutter ( 7896): #13 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4546:15) E/flutter ( 7896): #14 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11) E/flutter ( 7896): #15 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5) E/flutter ( 7896): #16 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5) E/flutter ( 7896): #17 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4710:11) E/flutter ( 7896): #18 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5) E/flutter ( 7896): #19 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14) E/flutter ( 7896): #20 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18) E/flutter ( 7896): #21 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16) E/flutter ( 7896): #22 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11) E/flutter ( 7896): #23 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5) E/flutter ( 7896): #24 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5) E/flutter ( 7896): #25 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4710:11) E/flutter ( 7896): #26 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5) E/flutter ( 7896): #27 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14) E/flutter ( 7896): #28 Element.updateChild (package:flutter/src/widgets/framework.dart:3258:18) E/flutter ( 7896): #29 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16) E/flutter ( 7896): #30 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5) E/flutter ( 7896): #31 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4525:5) E/flutter ( 7896): #32 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4520:5) E/flutter ( 7896): #33 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3490:14) E/flutter ( 7896): #34 Element.updateChild (package:flutter/src/widgets/framework.dart:3255:20) E/flutter ( 7896): #35 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4571:16) E/flutter ( 7896): #36 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4719:11) E/flutter ( 7896): #37 Element.rebuild (package:flutter/src/widgets/framework.dart:4262:5) E/flutter ( 7896): #38 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2667:33) E/flutter ( 7896): #39 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:866:20) E/flutter ( 7896): #40 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:286:5) E/flutter ( 7896): #41 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1117:15) E/flutter ( 7896): #42 SchedulerBinding.handleDrawFrame (package:flutter/src/schedule

Can you please help me to sort this thing.

Here is my configuration

static final GlobalKey<NavigatorState> navKey = OneContext().key;

and in the material app code:

navigatorKey: WlcmClubApp.navKey, builder: OneContext().builder,

routeName always return null

      OneContext().popUntil((route) {
        var name=route.settings.name;

        print("routeName:$name");
        return true;
      });


    routeName:null

Hey :wave:

Great package! : )
Just wondering about nested navigators. Do you have an example for this matter? 🤔

Can I use one_context to optimize my app size?

I was amazed at finding this package. My recurrent problem of app size just came to mind.

void main() => OnePlatform.app = () => LiteAppInstall();  // 5mb

// Later... Call reboot without recreating root app
OnePlatform.reboot();

// Later... Call reboot recreating the entire application
OnePlatform.reboot(
  builder: () => MainApp()    // 15Mb
);

// You even can load an entire different app
OnePlatform.reboot(
  builder: () => MyAppPremium().  //40Mb
);```

From the example above, Is it possible to externalize  MainApp and MyAppPremium for lazy downloaded if need by the user?
So my intention is to have my app listed on AppStore and Playstore as being ~= 5Mb in size.

OneContext().popAllDialogs() not working!!

OneContext().popDialog() is working without any problem but when I am trying to show multiple dialogs and close them I can't do that with OneContext().popAllDialogs().

showSnackbar crashed in modal dialog

  1. Open widget via showDialog.
  2. Call this code
OneContext().showSnackBar(
    builder: (_) => SnackBar(content: Text('My awesome snackBar!'))
);

Get error TypeError: this[_showSnackbar] is not a function.

Problems with the snackbar

Basically my problem is because I just wanted to use OneContext to display a snackbar since I found the package recently and it said it's so easy that I thought I'd use it.
But my surprise is when I simply execute the method shown in the README of the pub.dev page

// example snackBar
OneContext().showSnackBar(
     builder: (_) => SnackBar(content: Text('My awesome snackBar!'))
);

but it gave me an error that told me that I have to put a builder in the MaterialApp to have the context

return MaterialApp(
       builder: OneContext().builder,
       ....

That is why I come to create this error to ask that the package instructions be done correctly since it is being said that it is so easy and in the first test that I do it gives me an error.

It would be nice to explain that in order to have a global context, OneContext().builder must be used in the MaterialApp builder.

EXC_BAD_ACCESS Crashes on iOS for Flutter version 3.13.6

Hi,

I updated to Flutter 3.13.6 and one_context version ^2.1.0 crashed the app when it was it was distributed over the App Store with cryptic EXC_BAD_ACCESS errors (Simulator & Android worked fine.)

I tried out ^3.0.0-rc-1 which removed the crash, but the app still had issues so I had to removed the dependency.

flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 3.13.6, on macOS 14.0 23A344 darwin-arm64 (Rosetta), locale de-DE)
[!] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
✗ cmdline-tools component is missing
Run path/to/sdkmanager --install "cmdline-tools;latest"
See https://developer.android.com/studio/command-line for more details.
✗ Android license status unknown.
Run flutter doctor --android-licenses to accept the SDK licenses.
See https://flutter.dev/docs/get-started/install/macos#android-setup for more details.
[✓] Xcode - develop for iOS and macOS (Xcode 15.0.1)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2022.3)
[✓] VS Code (version 1.81.1)
[✓] Connected device (3 available)
[✓] Network resources

Olá! Parabéns pelo projeto!

Primeiramente gostaria de parabenizar pelo excelente package!

  • Também desenvolvi algo semelhante e chamei de asuka, era algo que utilizava localmente nos meus projetos, apenas pra snackbar e dialog. Gostaria de fazer algumas obvservações sobre o one_context.

  • Existe alguma forma de não colocar o context de forma estática? Por exemplo usando streams ou interfaces/listeners ou ficaria muito caro?
    O motivo da minha pergunta é que deixar o context estático é considerado ruim olhando as boas práticas da documentação link.

  • Vc planeja colocar testes unitários?

  • Fiz um fork e espero está contribuindo com o projeto em breve!
    De novo parabéns pelo projeto!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.