Edu*_*rdo 3 localization widget flutter
我正在构建一个演示应用程序来使用本地化字符串进行测试。我收到以下错误:
I/flutter (21588):在构建 MainApp(dirty) 时抛出了以下 NoSuchMethodError:I/flutter (21588):getter 'title' 在 null 上被调用。I/flutter (21588):接收者:null I/flutter (21588):尝试调用:title
我不确定为什么会收到此错误。我遵循了颤振文档上的指示。
我有以下本地化类:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'dart:async';
import 'package:bet_master/l10n/messages_all.dart';
class AppLocalizations {
static Future<AppLocalizations> load(Locale locale) {
final String name =
locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
final localeName = Intl.canonicalizedLocale(name);
return initializeMessages(localeName).then((bool _) {
Intl.defaultLocale = localeName;
return AppLocalizations();
});
}
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
String get title {
return Intl.message(
'Bet Master',
name: 'title',
desc: 'App Title'
);
}
String get search {
return Intl.message(
'Search',
name: 'search',
desc : ''
);
}
}
class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return ['en', 'es', 'fr'].contains(locale.languageCode);
}
@override
Future<AppLocalizations> load(Locale locale) {
return AppLocalizations.load(locale);
}
@override
bool shouldReload(AppLocalizationsDelegate old) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
对于 Home Widget 我只设置标题
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:bet_master/localization/localizations.dart';
void main() {
runApp(MainApp());
}
class MainApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
localizationsDelegates: [
const AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
supportedLocales: [
const Locale('en', ''),
const Locale('es', ''),
const Locale('fr', ''),
],
home: Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).title),
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
最后,问题似乎与本地化不可用有关,我将“主页”代码移动到另一个小部件并解决了该问题。
Widget build(BuildContext context) {
return new MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
_appLocalizationsDelegate,
],
supportedLocales: [
Locale('en'),
Locale('es'),
],
locale: _appLocalizationsDelegate.overridenLocale,
onGenerateTitle: (BuildContext context) => AppLocalizations.of(context).title,
home: Home()
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).title),
),
body: Column(children: <Widget>[
Text('hola'),
],)
);
}
}
Run Code Online (Sandbox Code Playgroud)
我仍然需要研究为什么需要这样做,但至少它现在有效。
| 归档时间: |
|
| 查看次数: |
2600 次 |
| 最近记录: |