测试:找不到MaterialLocalizations。 AppBar小部件需要提供MaterialLocalizations

时间:2019-02-24 12:57:22

标签: testing dart flutter

测试包含Scaffold()的全屏小部件时,出现此错误:

No MaterialLocalizations found.
AppBar widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.

我试图注入Localizations小部件,但错误仍然相同。有什么想法可以进行测试吗?

testWidgets('MiniScaffold', (WidgetTester tester) async {
    await tester.pumpWidget(Wrap(child: MiniScaffold()));
    expect(find.text('Hello'), findsOneWidget);
    await tester.pumpWidget(Container());
  });

class MiniScaffold extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Hello'),
          actions: <Widget>[],
        ),
        body: Container());
  }
}

class Wrap extends StatelessWidget {
  final Widget child;

  const Wrap({Key key, this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
        data: new MediaQueryData(),
        child: Localizations(
            locale: Locale('en-US'),
            delegates: [
              DefaultMaterialLocalizations.delegate,
              DefaultWidgetsLocalizations.delegate,
            ],
            child: Directionality(
              textDirection: TextDirection.ltr,
              child: this.child,
            )));
  }
}

1 个答案:

答案 0 :(得分:1)

最简单的解决方案是将Scaffold包装到MaterialApp

MaterialApp将同时包括本地化,媒体查询和其他一些您必须自己包括的内容。