Is there any example of useContext() function example? I want to use
AppLocalizations.of(context).someText
in many of hook widgets and I am not sure if it is just enough to wrap it in useEffect function on initialize.
Is there any example of useContext() function example? I want to use
AppLocalizations.of(context).someText
in many of hook widgets and I am not sure if it is just enough to wrap it in useEffect function on initialize.
I used useContext()
in my cubit helper function. It's global, but used inside of build()
methods in HookWidgets
:
void useCubitListener<BLOC extends Cubit<S>, S>(
BLOC bloc,
BlocListener<BLOC, S> listener, {
bool Function(S current)? listenWhen,
}) {
final context = useContext();
final listenWhenConditioner = listenWhen;
useMemoized(
() {
final stream =
bloc.stream.where(listenWhenConditioner ?? (state) => true).listen((state) => listener(bloc, state, context));
return stream.cancel;
},
[bloc],
);
}
and then:
useCubitListener<BookDetailsCubit, BookDetailsPageState>(cubit, (cubit, state, context) {
state.maybeWhen(
saveBook: () => context.router.pop<bool>(true),
deleteBook: () => context.router.pop<bool>(true),
orElse: () => null,
);
}, listenWhen: (state) => (state is BookDetailsPageSaveBook));
More on cubits and hooks here.
We can use like this.