felangel / flutter_services_binding

A subset of WidgetsFlutterBinding specifically for initializing the ServicesBinding.

Home Page:https://pub.dev/packages/flutter_services_binding

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

flutter_services_binding

ci coverage pub package style: very good analysis License: MIT

A subset of WidgetsFlutterBinding specifically for initializing the ServicesBinding.

When executing runApp within a custom Zone with zoneValues derived from the underlying platform we rely on WidgetsFlutterBinding.ensureInitialized():

final token = Object();
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final value = await _getPlatformValue();
  runZoned(
    () => runApp(MyApp()),
    zoneValues: {token: value},
  );
}

This appears to work as expected, however, because WidgetsFlutterBinding also initializes other bindings like GestureBinding the zoneValue is not accessible within onPressed callbacks:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print(Zone.current[token]); // OK
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              print(Zone.current[token]); // NULL
            },
            child: Text('Click Me'),
          ),
        ),
      ),
    );
  }
}

FlutterServicesBinding provides an API to initialize the ServicesBinding and SchedulerBinding independently of the remaining bindings in order to support accessing data from the underlying platform before runApp but without initializing the WidgetsBinding instance within the root Zone.

final token = Object();
void main() async {
  FlutterServicesBinding.ensureInitialized();
  final value = await _getPlatformValue();
  runZoned(
    () => runApp(MyApp()),
    zoneValues: {token: value},
  );
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print(Zone.current[token]); // OK
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              print(Zone.current[token]); // OK
            },
            child: Text('Click Me'),
          ),
        ),
      ),
    );
  }
}

About

A subset of WidgetsFlutterBinding specifically for initializing the ServicesBinding.

https://pub.dev/packages/flutter_services_binding

License:MIT License


Languages

Language:C++ 38.8%Language:CMake 28.2%Language:Dart 15.5%Language:HTML 7.3%Language:Ruby 5.0%Language:C 2.6%Language:Swift 2.4%Language:Kotlin 0.2%Language:Objective-C 0.1%