在Flutter中本地化小部件 [英] Localize a widget in Flutter
问题描述
我目前正在试驾,并且已经按照教程建立了本地化的"Hello world".一个>.但是,当我尝试将小部件移至其他文件时,出现红屏死机并显示错误:
I'm currently test driving and I have already built a localized "Hello world" following the tutorial. However, when I tried to move my widget to a different file, I got a red screen of death with the error:
The following NoSuchMethodError was thrown building ToDoItem(dirty):
The method 'helloWorld' was called on null.
Receiver: null
Tried calling: helloWorld()
我的待办事项类如下
todo_item.dart
import 'package:flutter/material.dart';
import 'package:to_do_app/localization.dart';
class ToDoItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Text(ToDoLocalizations.of(context).helloWorld());
}
}
当然,问题在于我的Localization类尚未初始化,但是由于Text
小部件没有LocalizationDelegates
参数,因此我不知道如何初始化它.
Of course the problem is that my Localization class has not been initialized, however I don't know how to initialize it since the Text
widget does not have a LocalizationDelegates
parameter.
我知道可以通过将String直接注入到我的小部件的构造函数中来解决此问题,但是出于这个原因,我想知道如何对小部件进行本地化.
I'm aware that this could be fixed by injecting the String directly into my widget's constructor, but for the sake of it I want to know how to localize widgets.
编辑:这是我的本地化课程
Here is my localization class
import 'dart:async';
import 'dart:developer';
import 'package:flutter/widgets.dart';
import 'package:intl/intl.dart';
import 'package:to_do_app/l10n/messages_all.dart';
class ToDoLocalizations {
ToDoLocalizations(Locale locale) : _localeName = locale.toString();
final String _localeName;
static Future<ToDoLocalizations> load(Locale locale) {
return initializeMessages(locale.toString()).then((Object _) {
return new ToDoLocalizations(locale);
});
}
static ToDoLocalizations of(BuildContext context) {
return Localizations.of<ToDoLocalizations>(context, ToDoLocalizations);
}
String helloWorld() {
return Intl.message(
'Hello, World!',
name: 'helloWorld',
desc: 'A friendly salutation',
locale: _localeName
);
}
}
class ToDoLocalizationsDelegate
extends LocalizationsDelegate<ToDoLocalizations> {
@override
bool isSupported(Locale locale) {
return ['en', 'nb'].contains(locale.languageCode);
}
@override
bool shouldReload(LocalizationsDelegate<ToDoLocalizations> old) {
return false;
}
@override
Future<ToDoLocalizations> load(Locale locale) {
return ToDoLocalizations.load(locale);
}
}
推荐答案
在严格遵循上述教程和本示例中概述的代码之后答案为我指明了正确的方向.我所有的代码都是正确的,唯一缺少的部分是使用相对路径而不是绝对路径编写import语句,然后错误消失了.
After closely following the aforementioned tutorial and the code outlined on this example repository without success, this answer pointed me in the right direction. All of my code was sound and the only missing part was to write import statements using relative paths instead of absolute paths and then the error disappeared.
这篇关于在Flutter中本地化小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!