1

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.

2 Answers 2

3

We can use like this.

Widget _getAccountRegister() {
    final context = useContext();
    return Container(
      margin: const EdgeInsets.all(10),
      child: FlatButton(
        padding: const EdgeInsets.all(10),
        onPressed: () {
          NavigationUtils.push(context, routeRegister);
        },
        child: Text(Localization.of(context).signIn),
      ),
    );
  }
2
  • 1
    It throws error => Failed assertion: line 609 pos 5: 'HookElement._currentHookElement != null': useContext can only be called from the build method of HookWidget.
    – hyobbb
    Jan 7, 2021 at 6:21
  • useContext is used only in the build method. I have called the above method _getAccountRegister() in the build method of the widget which is extended by HookWidget.
    – Mavya Soni
    Jan 7, 2021 at 7:58
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.