You can use any state management for that! For the sake of completion I'll use Riverpod
Step 1: Create a graphql_config.dart file and add this
final StateProvider<String> authTokenProvider =
StateProvider<String>((_) => '', name: 'tokenP');
final gqlClientProvider = Provider<ValueNotifier<GraphQLClient>>(
(ref) {
final String token = ref.watch(authTokenProvider).state;
final Link _link = HttpLink('YOUR_GRAPHQL_LINK', defaultHeaders: {
if (token.isNotEmpty) 'Authorization': 'Bearer $token',
});
return ValueNotifier(
GraphQLClient(
link: _link,
cache: GraphQLCache(store: HiveStore()),
),
);
},
name: 'gql Provider',
);
Step 2: Wrap your MaterialApp (main.dart file) with GraphQLProvider
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, ScopedReader watch) {
final client = watch(gqlClientProvider);
return GraphQLProvider(
client: client,
child: CacheProvider(
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'YOUR_APP_TITLE',
...
Step 3: Update token after successful login. Simply call the Provider and update the token
context.read(authTokenProvider).state ='YOUR_TOKEN';
PS. I didn't find a good example from the docs so I came up with this