在 Flutter 中测试本地化字符串
Posted
技术标签:
【中文标题】在 Flutter 中测试本地化字符串【英文标题】:Testing localized strings in Flutter 【发布时间】:2019-05-01 11:52:08 【问题描述】:当我尝试测试包含的 Widget 时
hintText: LocalizationResources.of(context).writecomment
我得到一个异常说:
The following NoSuchMethodError was thrown building CommentInput(dirty, state:
_CommentInputState#32224):
The getter 'writecomment' was called on null.
那么,我有什么遗漏的吗? 小部件可以很好地构建在设备和模拟器上。
这是我的测试的样子:
....
final Widget widget =
MaterialApp(home: CommentWallWidget(channelUid: '123456'), title: 'jelena',);
await tester.pumpWidget(widget);
而且 LocalizationResources 只是简单的 l10n:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'l10n/messages_all.dart';
///class containing localization logic and string getters
class LocalizationResources
static Future<LocalizationResources> load(Locale locale)
final String name =
locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
final String localeName = Intl.canonicalizedLocale(name);
return initializeMessages(localeName).then((_)
Intl.defaultLocale = localeName;
return LocalizationResources();
);
static LocalizationResources of(BuildContext context)
return Localizations.of<LocalizationResources>(
context, LocalizationResources);
....
【问题讨论】:
【参考方案1】:您需要将您的测试小部件包装在MediaQuery
小部件中并提供您的本地化委托。有关更多示例,请参阅here。
final Widget widget = MediaQuery(
data: MediaQueryData(),
child: MaterialApp(
localizationsDelegates: [LocalizationResourcesDelegate()],
home: CommentWallWidget(channelUid: '123456'),
title: 'jelena',
)
);
【讨论】:
以上是关于在 Flutter 中测试本地化字符串的主要内容,如果未能解决你的问题,请参考以下文章