Flutter Gen使用报错:AssetGenImage无法赋值给ImageProvider参数
使用flutter gen加载图片时的类型不匹配问题
我在使用flutter gen包初始化图片时遇到了类型不匹配的错误,以下是我的代码实现:
Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image(image: Assets.images.logo, height: 64),//错误位置 const SizedBox( height: 32, ), const SpinKitFadingCube( color: Solidcolors.primaryColor, size: 32.0, ) ], ), ), ); } }
出现的错误提示:
The argument type 'AssetGenImage' can't be assigned to the parameter type 'ImageProvider'
生成文件的代码如下:
import 'package:flutter/widgets.dart'; class $AssetsImagesGen { const $AssetsImagesGen(); /// File path: assets/images/logo.png AssetGenImage get logo => const AssetGenImage('assets/images/logo.png'); } class Assets { Assets._(); static const $AssetsImagesGen images = $AssetsImagesGen(); }
解决方案
问题原因是AssetGenImage是flutter gen封装的自定义类型,而Image组件的image参数需要的是ImageProvider类型。有两种简单的解决方式:
- 方式一:调用
AssetGenImage的image()方法获取ImageProvider
Image(image: Assets.images.logo.image(), height: 64)
- 方式二:直接使用
AssetGenImage提供的widget属性,直接得到配置好的Image组件(更简洁)
Assets.images.logo.image(height: 64)
内容的提问来源于stack exchange,提问作者Mohammad.Tlb
相关产品推荐
相关产品推荐

