我目前正在测试驾驶,并且已经按照教程构建了本地化的“ Hello world” 。但是,当我尝试将窗口小部件移至其他文件时,出现红屏死机并显示以下错误:
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参数,我不知道如何初始化它。
Text
LocalizationDelegates
我知道可以通过将String直接注入到我的小部件的构造函数中来解决此问题,但是出于这个原因,我想知道如何本地化小部件。
编辑: 这是我的本地化课程
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语句,然后错误消失了。