Closed iSaqibShafique closed 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.
// 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),
),
);
}
}
Thank you so much sir for your time. ❤️
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),
),
);
}
}