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.

hyobbb
  • 332
  • 1
  • 9

2 Answers2

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),
      ),
    );
  }
Mavya Soni
  • 932
  • 7
  • 15
  • 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 07 '21 at 06: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 07 '21 at 07: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.

lomza
  • 9,412
  • 15
  • 70
  • 85