【问题标题】:Write flutter widget tests that uses GoogleFonts编写使用 Google 字体的颤振小部件测试
【发布时间】:2021-03-19 15:21:48
【问题描述】:

我需要编写一个颤振小部件测试来测试使用 GoogleFonts 插件的小部件。但是,它给出了正确的网络故障,因为测试套装无法访问互联网。问题是 GoogleFonts.majorMonoDisplayTextTheme 是一个静态方法,在小部件测试中使用时无法模拟 GoogleFont 类。

Error: google_fonts was unable to load font MajorMonoDisplay-Regular because the following exception occurred: 
Exception: Failed to load font with URL: https://fonts.gstatic.com/s/a/9901077f5681d4ec7e01e0ebe4bd61ba47669c64a7aedea472cd94fe1175751b.ttf

小部件使用:

 Container(
      padding: EdgeInsets.only(top: 10),
      child: Text(
        _now,
        style: GoogleFonts.majorMonoDisplayTextTheme(Theme.of(context).textTheme).headline3,
      ),
    ),

小部件测试方法:

testWidgets(
  'Shoudl display _now text',
  (WidgetTester tester) async {
  await tester.pumpWidget(_TestWidgetWithGoogleFont);
  await tester.pumpAndSettle();
  expect(find.byType(Text), findsOneWidget);
});

【问题讨论】:

    标签: flutter mobile flutter-test google-fonts


    【解决方案1】:

    还有另一种方法可以消除错误。如果您不想(或不能)向项目添加其他文件,则特别方便。

    只需将这行代码添加到所需的测试中:

    setUp(() => GoogleFonts.config.allowRuntimeFetching = false);
    

    此代码不允许运行时提取,这是一个首先引发错误的过程。

    【讨论】:

      【解决方案2】:

      首先你必须在 pubspec.yaml 文件中提供字体 只需按照这些步骤 下载堡垒解压它。 转到您的项目文件并创建一个名为“assets”的文件夹,然后在 assets 文件夹中创建另一个名为“fonts”的文件夹。在这个字体文件夹中粘贴字体 .tiff 复制文件名,在这种情况下它是“MajorMonoDisplay-Regular.ttf”

      接下来您必须在 pubspec.yaml 文件中提供字体信息 只需复制粘贴这些代码即可。

        fonts:
      - family: MajorMonoDisplay
        fonts:
          - asset: assets/fonts/MajorMonoDisplay-Regular.ttf
      

      接下来在打开的终端中运行“flutter pub get” 现在只需在您的 TextStyle 中提供堡垒家族。 示例:

      child: Column(
                    children: [
                      Text(
                        'Should display _now text',
                        style: TextStyle(
                          fontSize: 20,
                          fontFamily: 'MajorMonoDisplay',
                        ),
                      )
                    ],
                  ),
      

      如果前面没有显示,请关闭应用程序并重新运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-11
        • 2020-05-13
        • 1970-01-01
        • 1970-01-01
        • 2020-03-03
        • 1970-01-01
        • 2021-06-11
        • 2018-10-18
        相关资源
        最近更新 更多