I'm migrating my Flutter project from GetX to Riverpod and encountered an error with using watch
in Riverpod's Consumer
. The error message is: "The expression doesn't evaluate to a function, so it can't be invoked", specifically pointing to the usage of watch
(countDownControllerProvider).state.isAnimating.
Here's the problematic code snippet:
child: Consumer(
builder: (context, watch, child) {
// Error occurs here
final startPausedText = watch(countDownControllerProvider).state.isAnimating;
// Rest of the code...
},
);
Complete code context:
final countDownControllerProvider =
StateProvider<CountDownController>((ref) => CountDownController());
class StartStopGroupButton extends ConsumerStatefulWidget {
const StartStopGroupButton({Key? key}) : super(key: key);
@override
ConsumerState<StartStopGroupButton> createState() =>
_StartStopGroupButtonState();
}
class _StartStopGroupButtonState extends ConsumerState<StartStopGroupButton> {
late final countDownController;
@override
void initState() {
super.initState();
countDownController = ref.read(countDownControllerProvider);
}
@override
Widget build(BuildContext context, ) {
return Scaffold(
backgroundColor: Colors.grey,
body: Center(
child: Consumer(
builder: (ref, watch, child) {
final startPausedText =
watch(countDownControllerProvider).state.isAnimating;
return FloatingActionButton.extended(
heroTag: 'btn1',
elevation: 0,
backgroundColor: Colors.white,
onPressed: countDownController.startPaused,
label: Text(
startPausedText,
style: TextStyle(
color: Colors.black,
fontSize: 24.0,
),
),
);
},
),
),
);
}
}
Can anyone explain why this error occurs and how to resolve it using watch
with Riverpod?
Thank you for any assistance or guidance.
builder: (ref, watch, child)
is not the proper parameters for a Consumer
. You want (context, ref, child)
. And then you'll call ref.watch
to do what you're trying to do with just watch