I am a beginner in flutter and making an app and I implemented localization but when I exit and re enter the app it just goes back to default language. How do I save the selected language to show when I restart the app? This is the language changing page where list of languages will be located.
class LanguageSelector extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
children: [
Padding(
padding: EdgeInsets.all(4.0.wp),
child: Row(
children: [
IconButton(
onPressed: () {
Get.back();
},
icon: const Icon(Icons.arrow_back),
)
],
),
),
Padding(
padding: EdgeInsets.all(4.0),
child: ListTile(
title: Text(
'English',
style: TextStyle(fontSize: 12.0.sp),
),
onTap: () {
var locale = Locale('en', 'US');
Get.updateLocale(locale);
},
),
),
Padding(
padding: EdgeInsets.all(4.0),
child: ListTile(
title: Text(
'Croatian',
style: TextStyle(fontSize: 12.0.sp),
),
onTap: () {
var locale = Locale('hr', 'HR');
Get.updateLocale(locale);
},
),
),
],
),
),
);
}
}
And this is in the main.dart file.
void main() async {
await GetStorage.init();
await Get.putAsync(() => StorageService().init());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
translations: LocalString(),
locale: Locale('en', 'US'),
title: 'Todo List',
theme: Themes().lightTheme,
darkTheme: Themes().darkTheme,
themeMode: ThemeService().getThemeMode(),
home: const HomePage(),
debugShowCheckedModeBanner: false,
initialBinding: HomeBinding(),
builder: EasyLoading.init(),
);
}
}
One way to do this is to save the required data in shared_preferences. So each time you load the app we can retrieve the data stored in the mobile and use it to decide the initial state of the app.
Example code of use:
final prefs = await SharedPreferences.getInstance();
final String? language = prefs.getString('lang');
if(language == null){
prefs.setString('lang', 'eng');
language = 'eng';
}