rodydavis / signals.dart

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

Signals not working in a separate class #251

Closed iSaqibShafique closed 2 months ago

iSaqibShafique commented 2 months ago

Hey, hope you're good. I'm curious why Signals aren't firing inside a class, it does work when outside a class but that's hard to manage the code. Check out the example below. Looking forward to your insights. Thanks!

// Controller code, with functions & Signals

class DemoPageController { final Signal counter = Signal(0); increment() { counter.value++; } }

// UI Code

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

@override Widget build(BuildContext context) { DemoPageController controller = DemoPageController(); return Scaffold( appBar: AppBar( title: const Text('Flutter Counter'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'You have pushed the button this many times:', ), Text( controller.counter.watch(context).toString(), style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () => controller.increment(), tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }

rodydavis commented 2 months ago

You are creating a new controller every time the build method runs.

You should pass in the controller to the widget constructor.

rodydavis commented 2 months ago
// Controller code, with functions & Signals

class DemoPageController {
final Signal counter = Signal(0);
increment() {
counter.value++;
}
}

// UI Code

class CounterExample extends StatelessWidget {
const CounterExample({
  super.key,
+  required this.controller,
});

+ final DemoPageController controller;

@OverRide
Widget build(BuildContext context) {
- DemoPageController controller = DemoPageController();
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Counter'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pushed the button this many times:',
),
Text(
controller.counter.watch(context).toString(),
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => controller.increment(),
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
iSaqibShafique commented 2 months ago

Thank you so much sir for your time. ❤️