Skip to content

Instantly share code, notes, and snippets.

@TesteurManiak
Last active February 27, 2024 15:32
Show Gist options
  • Select an option

  • Save TesteurManiak/d2408df69ebd37bdff5a364ffdc84901 to your computer and use it in GitHub Desktop.

Select an option

Save TesteurManiak/d2408df69ebd37bdff5a364ffdc84901 to your computer and use it in GitHub Desktop.
Flutter code sample to manage localization using riverpod
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class LocalizationNotifier extends StateNotifier<Locale?> {
LocalizationNotifier({
required this.defaultLocale,
required this.supportedLocales,
}) : super(defaultLocale);
final Locale defaultLocale;
final List<Locale> supportedLocales;
Future<void> loadLocale() async {
// Load the locale from the storage, then set the state accordingly.
state = const Locale('en');
}
Future<void> setLocale(Locale locale) async {
if (!supportedLocales.contains(locale)) return;
// Save your locale for future usage then set the state.
state = locale;
}
}
final localizationProvider =
StateNotifierProvider.autoDispose<LocalizationNotifier, Locale?>(
(ref) {
final defaultLocale = ref.watch(defaultLocaleProvider);
final supportedLocales = ref.watch(supportedLocalesProvider);
return LocalizationNotifier(
defaultLocale: defaultLocale,
supportedLocales: supportedLocales,
);
},
);
final supportedLocalesProvider = Provider<List<Locale>>(
(ref) => const [Locale('fr'), Locale('en')],
);
final defaultLocaleProvider = Provider<Locale>(
(ref) => const Locale('en'),
);
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final container = ProviderContainer();
final localizationNotifier = container.read(localizationProvider.notifier);
await localizationNotifier.loadLocale();
runApp(
UncontrolledProviderScope(
container: container,
child: MyApp(),
),
);
}
class MyApp extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final locale = ref.watch(localizationProvider);
final supportedLocales = ref.watch(supportedLocalesProvider);
return MaterialApp(
locale: locale,
supportedLocales: supportedLocales,
debugShowCheckedModeBanner: false,
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
ref
.read(localizationProvider.notifier)
.setLocale(const Locale('fr'));
},
child: const Text('fr'),
),
body: const Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Text(Localizations.localeOf(context).toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment