Here is my Custom reusable Widget code.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class MyFloatingActionButton extends ConsumerWidget {
final Function(ProviderRef ref) onPressed;
MyFloatingActionButton(this.onPressed);
@override
Widget build(BuildContext context, WidgetRef ref) {
return FloatingActionButton(
onPressed: () => onPressed,
tooltip: 'Increment',
child: Icon(Icons.add),
);
}
}
Here is the the parent widget :
floatingActionButton: MyFloatingActionButton((ref) => ref.read(myProvider)._increase())
Here is myProvider
class CountNotifier extends ChangeNotifier {
int num = 0;
void _increase() {
num ++;
notifyListeners();
}
}
final myProvider = ChangeNotifierProvider((ref) {
return CountNotifier();
});
After passinging the Function to its child its not working anymore. But in the parent widget it just working fine.
I am expecting to pass ref.read() function to any child widget.
2
Answers
Your callback function won’t be called as your code:
Because
() => onPressed
means a function always returns a value, and the value is your callback function. You have never called your callback function!So you should call it like this:
() => onPress(ref)
.I don’t know what you want to implement, but my suggestion is just only to use the
ref
from the parent widget, don’t pass theref
by hand.Try it like this:
child: