rodydavis / signals.dart

Reactive programming made simple for Dart and Flutter
http://dartsignals.dev
Apache License 2.0
378 stars 44 forks source link

Add lite_ref example to docs and fix error in SignalProvider example #235

Closed jinyus closed 2 months ago

jinyus commented 2 months ago

Lite Ref

Lite Ref is a simple way to provide disposable objects to your widgets.

final counterRef = Ref.scoped(
  (_) => signal(0),
  dispose: (instance) => instance.dispose(),
);

void main() {
  runApp(LiteRefScope(child: MyApp()));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final counter = counterRef.of(context);
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Signals with Zones'),
        ),
        body: Center(
          child: Watch((context) => Text('Value: $counter')),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () => counter.value++,
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

You can use any class that implements Disposable and it will be disposed when the widget is removed from the widget tree. You also don't need to provide a dispose function for the ScopedRef.

class Counter implements Disposable {
  final value = signal(0);
  final doubled = computed(() => value.value * 2);

  @override
  void dispose() {
    value.dispose();
    doubled.dispose();
  }
}

final counterRef = Ref.scoped((_) => Counter());