Pub Star on Github License: MIT


Simple Ref

A simple, lightweight and auto disposable service locator reference library with overrides support for Flutter.

Installation

flutter pub add --dev simple_ref

Usage

Import package:

import 'package:simple_ref.dart';

Singleton References:

final repositoryRef = Ref(() => Repository());

// or with tear-off
final repositoryRef = Ref(Repository.new);

// Access the instance
final repository = repositoryRef();

// Override
repositoryRef.overrideWith(() => MockRepository());

For AutoDispose, wrap your app with a RefScope:

runApp(
    const RefScope(
        child: MyApp(),
    ),
);

Implement, Extend or Mixin a Disposable and override the dispose method:

class Controller implements Disposable {
  final counter = ValueNotifier(0);

  @override
  void dispose() {
    counter.dispose();
  }
}

Create a AutoDisposeRef:

final controllerRef = Ref.autoDispose((_) => Controller());

Access the instance:

This can be done in a Widget or in a Ref by using controllerRef.of(context) or controllerRef(context).

class CounterPage extends StatelessWidget {
    const CounterPage({super.key});

    @override
    Widget build(BuildContext context) {
        final controller = controllerRef.of(context);
        return Text('${controller.counter.value}');
    }
}

Override it:

You can override the instance by using overrideWith. This is useful for testing or for initiate the async instances. In the example below, all calls to controllerRef.of(context) will return MockController.

controllerRef.overrideWith((context) => MockController());

Libraries

simple_ref
A simple and lightweight service locator library for Flutter.