这是我更改语言环境时所得到的:
if (newLang is! String) return;
_language = newLang;
changeLocale(context, newLang);
Locale(newLang, ''); // method 1
MyApp.of(context)!.setLocale(Locale.fromSubtags(languageCode: newLang)); // method 2
Provider.of<TimesAp>(context, listen: false).changeLanguage(newLang); // method 3
});
如您所见,我添加了 2 个正在检查的额外方法,但它们似乎都不起作用,所以我认为问题可能出在其他地方。
void setLocale(Locale value) {
setState(() {
_locale = value; // method 2
});
}
@override
Widget build(BuildContext context) {
final localizationDelegate = LocalizedApp.of(context).delegate;
return MultiProvider(
providers: [
ChangeNotifierProvider<TimesAp>(create: (_) => TimesAp()), // method 3
],
child: MaterialApp(
debugShowCheckedModeBanner: false,
// locale: getSavedLanguage(context),
locale: _locale, // method 2
supportedLocales: localizationDelegate.supportedLocales,
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
localizationDelegate
],
方法3:
class TimesAp extends ChangeNotifier {
String locale = 'en';
changeLanguage(String newLang) {
locale = newLang;
updateUI();
}
updateUI() {
notifyListeners();
}
}
我有登陆和选项页面,我可以在其中进行语言更新。对于该页面,一切都发生了变化,但当我返回时,一切都没有改变。当我刷新时它会发生(我将其保存在共享首选项中)。
https://zapp.run/edit/flutter-z7ec06l27ed0?entry=lib/main.dart&file=lib/options.dart
缺少 2 件事:
LocalizationProvider(
state: LocalizationProvider.of(context).state,
child: MaterialApp(
和
home:
无法返回 const