Closed yousefak007 closed 11 months ago
This can be done in initState with subscribe or an effect
This can be done in initState with subscribe or an effect
However, you cannot use initState if you use a Builder widget or something similar. In those cases, I use useEffect from Flutter Hooks to call subscribe or effect. However, I would love it if there was a handier way to do it.
Do you mean use a widget that needs the build context? For that you can add a post frame callback
so i juse use useEffecte with addPostFrame callback to get initState behaviour
as example bloc have a listener
BlocListener<BlocA, BlocAState>(
listener: (context, state) {
// do stuff here based on BlocA's state
},
child: Container(),
)
also here riverpod it is more elegant
Widget build(BuildContext context, WidgetRef ref) {
ref.listen(otherProvider, (previous, next) {
print('Changed from: $previous, next: $next');
});
...
}
Added listen
on 1.5.4!
Example:
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final Signal<int> counter = signal(0, debugLabel: 'Counter');
void _incrementCounter() {
counter.value++;
}
@override
Widget build(BuildContext context) {
counter.listen(context, () {
if (counter.value == 10) {
final messenger = ScaffoldMessenger.of(context);
messenger.hideCurrentSnackBar();
messenger.showSnackBar(
const SnackBar(content: Text('You hit 10 clicks!')),
);
}
});
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: [
Builder(builder: (context) {
final dark = isDark.watch(context);
return IconButton(
onPressed: () {
brightness.value = dark ? Brightness.light : Brightness.dark;
},
icon: Icon(dark ? Icons.light_mode : Icons.dark_mode),
);
}),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Watch((context) {
return Text(
'$counter',
style: Theme.of(context).textTheme.headlineMedium!,
);
}),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
Nice, this is really convenient! 👍🏻
maybe it will be nice if we can listen to signal from the build method without rebuild widget for showing snackbar or anything else