I folowed this video to implement localization in my app :- https://youtu.be/Zw4KoorVxgg
Everything works fine but when the app is relaunched the language gets set to default. How can I persiste the data.
[Note:- I am already using shared preference to persist some other data in my app, but I have no clue about persisting selected Locale]This class below is called to set the locale:
class LocaleProvider extends ChangeNotifier {
Locale? _locale;
Locale? get locale => _locale;
void setLocale(Locale locale) {
if (!L10n.all.contains(locale)) return;
_locale = locale;
notifyListeners();
}
void clearLocale() {
_locale = null;
notifyListeners();
}
}
And this is the screen where I set the language:
class SelectLanguage extends StatefulWidget {
const SelectLanguage({Key? key}) : super(key: key);
@override
_SelectLanguageState createState() => _SelectLanguageState();
}
class _SelectLanguageState extends State<SelectLanguage> {
void setLocale(String selectedLocale) {
final provider = Provider.of<LocaleProvider>(context, listen: false);
provider.setLocale(
Locale(selectedLocale),
);
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Colors.black,
body: Padding(
padding:
EdgeInsets.all(MediaQuery.of(context).size.width / 41.1),
child: GridView(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 2.75,
crossAxisSpacing: MediaQuery.of(context).size.width / 41.1,
mainAxisSpacing: MediaQuery.of(context).size.width / 41.1,
),
children: [
LanguageTile(
tileTitle: 'English',
titleOnTap: () => setLocale('en'),
),
LanguageTile(
tileTitle: 'हिन्दी',
titleOnTap: () => setLocale('hi'),
),
],
),
),
),
);
}
}
2
Answers
using shared preference
create a class
then in your provider class add
where or widget you are implementing it e.g dropdown
and in the main.dart change to stateful and override
hope this helps