搜尋套件、儲存庫與 APP 分類

套件詳情v4.1.0

one_context

OneContext 提供了一種簡單的方法來處理對話框、覆蓋層、導航、主題* 和 MediaQuery*,而不需要使用 BuildContext。

AndroidiOSWebmacOSWindowsLinux
近 30 天下載
1160
喜歡數
209
Pub 分數
140

安裝套件

flutter pub add one_context

套件介紹

根據套件公開資料產生的選型評估,僅供參考。

OneContext 是一個 Flutter/Dart 套件,可簡化處理對話方塊、覆蓋層、導航以及存取主題和媒體查詢資料,而不需要使用 BuildContext。它提供全域方法來管理整個 widget 樹中的應用程式狀態和 UI 互動,讓從應用程式的任何地方顯示警示、導航或取得與上下文相關的值變得更容易。非常適合減少重複程式碼並提升複雜 Flutter 應用程式的程式碼可維護性。

適用情境

  • 顯示對話框時沒有 BuildContext
  • 應用中的全域導航
  • 全域存取主題和媒體查詢資料
  • 管理疊加層和彈出視窗
  • 簡化UI元素的狀態管理
  • 減少對BuildContext的依賴,以在工具函數中使用

主要特色

  • 無需 BuildContext
  • 全域對話框與覆蓋層管理
  • 從任何位置輕鬆導航
  • 全域存取 Theme 與 MediaQuery
  • 最少的樣板程式碼
  • 跨平台支援

適合對象

  • 大規模 Flutter 應用
  • 尋求更簡單上下文處理的開發者
  • 頻繁彈出對話框和覆蓋層的應用
  • 希望保持一致 UI 行為的團隊
  • 旨在減少 BuildContext 依賴的專案
  • 需要全域存取的實用函數

使用建議

  • 可能跳過標準 widget 生命週期
  • 在簡單情況下有過度使用的潛在風險
  • 需要仔細的狀態管理
  • 不適合用於深度嵌套的上下文相關邏輯
  • 有限的除錯可見性
  • 最佳搭配清晰的架構邊界使用

原始 README

以下為關聯原始碼儲存庫的 README 原文快照,最新內容請造訪原始碼儲存庫。

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

所屬分類

依賴

依賴清單 2 項

原始碼儲存庫

使用此套件的專案

暫無相關資料。