将新的MaterialPageRoute推送到导航器时,语言环境为null

时间:2019-07-06 21:12:40

标签: flutter dart

当我使用Navigator导航到应用程序中的不同视图时,会得到NPE。

要克服此错误,我可以在导航器中包装以下内容:

MaterialApp(localizationsDelegates: [
  AppLocalizationsDelegate(),
  GlobalMaterialLocalizations.delegate,
  GlobalWidgetsLocalizations.delegate
], supportedLocales: [
  Locale('en'),
  Locale('es'),
  Locale('hi')
], home: MyNewView())

要获取我的l10n个特定的字符串,我调用Localizations.of(context,AppLocalizations)。在这里可以返回空值,因为Localizations.of()调用InheritedFromWidgetOfExactType来获取在小部件树上定义的AppLocalizations。

目前,我不确定在导航时是否需要将每个新页面路线都包装在材质应用中。我认为自从这样启动应用程序以来,语言环境将可用。其他人有没有经历过?

runApp(MaterialApp(localizationsDelegates: [
  AppLocalizationsDelegate(),
  GlobalMaterialLocalizations.delegate,
  GlobalWidgetsLocalizations.delegate
], supportedLocales: [
  Locale('en'),
  Locale('es'),
  Locale('hi')
], home: MyApp(loginBloc, title: title)))

这是我的代表代码:

import 'package:flutter/material.dart';
import 'package:frontend/locale/locales.dart';

class AppLocalizationsDelegate extends 
LocalizationsDelegate<AppLocalizations> {
 @override
 bool isSupported(Locale locale) {
  return ['en', 'es', 'hi', 'es_US'].contains(locale.languageCode);
 }

@override
Future<AppLocalizations> load(Locale locale) async {
 final AppLocalizations localizations = await 
 AppLocalizations.load(locale);
 return localizations;
}

@override
bool shouldReload(LocalizationsDelegate<AppLocalizations> old) {
 return false;
 }
}

0 个答案:

没有答案