flutter hook useContext example

2.1k views Asked by At

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

There are 2 answers

2
Mavya Soni On BEST ANSWER

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),
      ),
    );
  }
0
lomza On

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.