void main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => LanguageCubit(),
child: BlocBuilder<LanguageCubit, Locale>(builder: (context, lang) {
return MaterialApp(
locale: lang,
title: 'Localizations Sample App',
localizationsDelegates: [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: [
const Locale('en', ''), // English, no country code
const Locale('es', ''), // Spanish, no country code
const Locale('tr', ''),
const Locale('it', ''),
],
home: Home(),
);
}),
);
}
}
class Home extends StatelessWidget {
const Home({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
color: Colors.amberAccent,
width: 200,
height: 200,
child: Column(
children: [
Text(AppLocalizations.of(context).helloWorld),
Divider(),
TextButton(
onPressed: () {
context.read<LanguageCubit>().changeLangEs(context);
},
child: Text('Change')),
],
),
),
),
);
}
}
class LanguageCubit extends Cubit<Locale> {
LanguageCubit() : super(null);
static final _languageEn = Locale('en', '');
static final _languageEs = Locale('es', '');
static final _languageTr = Locale('tr', '');
void changeLangEn(context) async {
emit(_languageEn);
}
void changeLangEs(context) async {
emit(_languageEs);
}
void changeLangTr(context) async {
emit(_languageTr);
}
}
I have such an application, the problem is that when I close the application and open it, the application uses the default language again.How can I permanently change the application language to the chosen language?It would be great if an example is given through this code.Do I need to store the chosen language and then use it from that db? Does Flutter_localizations offer a simple way to do this?
I used a method like this and it works great, simple and useful.
context.read<LanguageCubit>().changeStartLang();
inbuild