【问题标题】:How to test Image widgets source path in Flutter如何在 Flutter 中测试图像小部件的源路径
【发布时间】:2021-04-24 23:45:13
【问题描述】:

我有以下设置:

return Container(
      child: widget.searchResult.companyLogoUrl.isEmpty
          ? Image.asset('assets/images/missing-company-logo.png')
          : Image.network(widget.searchResult.companyLogoUrl),
    )

现在我想测试在没有提供 url 时是否加载了丢失的徽标图像。 测试中获取Image小部件后如何获取源url或本地文件?

testWidgets('given', (tester) async {
      await tester.pumpWidget(createSearchResultCard(mockResponse));
      await tester.pumpAndSettle();
      final Image image = find.byType(Image).evaluate().single.widget as Image;
      final String source = image. // How do I get the file source?
      expect(...)
    });

有没有办法知道加载了哪张图片?

【问题讨论】:

    标签: image flutter flutter-layout flutter-test


    【解决方案1】:

    使用Image 小部件类的image 属性检查图像提供程序是什么。从那里您可以提取单个属性:

    String source;
    if(image.image is AssetImage) {
      source = image.image.assetName;
    } else if(image.image is NetworkImage) {
      source = image.image.url;
    }
    

    您可以根据需要扩展他以包含更多可能的图像提供者。

    【讨论】:

    • 它有效。在 if 情况下,我不得不再次对 image.image 进行类型转换,但之后一切顺利。
    猜你喜欢
    • 2022-06-24
    • 2019-10-31
    • 2022-12-12
    • 2019-02-25
    • 2019-06-11
    • 2019-06-13
    • 2021-05-09
    • 2020-03-21
    • 2020-02-26
    相关资源
    最近更新 更多