flutter_localization_tutorial icon indicating copy to clipboard operation
flutter_localization_tutorial copied to clipboard

How to change app language on click of a button?

Open developers-qquick opened this issue 5 years ago • 1 comments

How to change app language on click of a button and without restarting the app ?

developers-qquick avatar Jun 13 '20 11:06 developers-qquick

you need to add a static method in your myApp , i.e

class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState();

static _MyAppState of(BuildContext context) => context.findAncestorStateOfType<_MyAppState>(); }

class _MyAppState extends State<MyApp> { Locale _locale;

void setLocale(Locale value) { setState(() { _locale = value; }); }

@override Widget build(BuildContext context) { return MaterialApp( locale: _locale, home: Dashboard(), ); } }

class Dashboard extends StatelessWidget { @override Widget build(BuildContext context) { return Column( children: [ TextButton( child: Text("Set locale to English"), onPressed: () => MyApp.of(context).setLocale(Locale.fromSubtags(languageCode: 'en')), ), TextButton( child: Text("Set locale to EK"), onPressed: () => MyApp.of(context).setLocale(Locale.fromSubtags(languageCode: 'ek')), ), ], ); } }

MrShafqatNadeem avatar Apr 14 '22 07:04 MrShafqatNadeem