gpt4 book ai didi

flutter - 小部件测试期间无法加载 Assets SVG

转载 作者:行者123 更新时间:2023-12-05 01:58:16 24 4
gpt4 key购买 nike

我想在我的一些屏幕上做一个小部件测试,其中包括 SvgPicture 小部件,但我不能这样做,因为它会抛出异常。

重现错误的代码:

import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_test/flutter_test.dart';


void main() {
testWidgets(
'SvgPicture.asset passes',
(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: SvgPicture.asset('icons/pencil.svg'),
),
));
await tester.pump();
},
);
}

执行结果:

══╡ EXCEPTION CAUGHT BY SVG ╞═══════════════════════════════════════════════════════════════════════
The following assertion was thrown resolving a single-frame picture stream:
Unable to load asset: icons/pencil.svg

When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:224:7)
<asynchronous suspension>
<asynchronous suspension>
(elided one frame from package:stack_trace)
...

Picture provider: ExactAssetPicture(name: "icons/pencil.svg", bundle: null, colorFilter: null)
Picture key: AssetBundlePictureKey(bundle: PlatformAssetBundle#c2c00(), name: "icons/pencil.svg",
colorFilter: null)
════════════════════════════════════════════════════════════════════════════════════════════════════

如何通过考试?

最佳答案

只需创建假的 AssetBundle 并用它包装整个应用程序:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';

class FakeAssetBundle extends Fake implements AssetBundle {
final String svgStr = '''<svg viewBox="0 0 10 10"></svg>''';

@override
Future<String> loadString(String key, {bool cache = true}) async => svgStr;
}

void main() {
testWidgets(
'SvgPicture.asset passes',
(WidgetTester tester) async {
await tester.pumpWidget(DefaultAssetBundle(
bundle: FakeAssetBundle(),
child: MaterialApp(
home: Scaffold(
body: SvgPicture.asset('icons/pencil.svg'),
),
),
));
await tester.pump();
},
);
}

关于flutter - 小部件测试期间无法加载 Assets SVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68653117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com