I have tried to use easy_localization with provider package. I can't figure out where to use EasyLocalization.of(context).locale = <
@Melak12
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
log(EasyLocalization.of(context).locale.toString(),
name: this.toString() + "# locale");
log("title".tr().toString(), name: this.toString() + "# locale");
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (_) => MyProvider(EasyLocalization.of(context))), //<-- send to provider
],
child: MaterialApp(
title: 'title'.tr(),
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
EasyLocalization.of(context).delegate,
],
supportedLocales: EasyLocalization.of(context).supportedLocales,
locale: EasyLocalization.of(context).locale,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Easy localization'),
),
);
}
}
Example provider
class MyProvider with ChangeNotifier {
dynamic easyLocalization;
MyProvider(this.easyLocalization); // <--- get EasyLocalization
void changeLocale(Locale locale) {
easyLocalization.locale = locale; // <--- change locale
notifyListeners();
}
}
Call change locale on Widgets
onTap: () {
Provider.of<MyProvider>(context, listen: false).changeLocale(Locale('en', 'US'));
}
@aissat maybe add this in documentation?
@aissat and maybe need make public _EasyLocalizationProvider for share type?
class MyProvider with ChangeNotifier {
EasyLocalizationProvider easyLocalization; //<-- like this
....
}
This is perfect and works like a charm! Thanks, @Overman775! You better add this to the documentation.
Hi,
The solution is not working. I followed all the steps by the below error catched:
โโโโโโโโ Exception caught by gesture โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The following assertion was thrown while handling a gesture:
Tried to listen to an InheritedWidget in a life-cycle that will never be called again.
This error typically happens when calling Provider.of with `listen` to `true`,
in a situation where listening to the provider doesn't make sense, such as:
- initState of a StatefulWidget
- the "create" callback of a provider
This is undesired because these life-cycles are called only once in the
lifetime of a widget. As such, while `listen` is `true`, the widget has
no mean to handle the update scenario.
To fix, consider:
- passing `listen: false` to `Provider.of`
- use a life-cycle that handles updates (like didChangeDependencies)
- use a provider that handles updates (like ProxyProvider).