在Flutter中添加图片和字体

介绍
Flutter应用程序可以包含代码和 assets
(有时称为资源)。asset
是打包到程序安装包中的,可在运行时访问。常见类型的asset
包括静态数据(例如JSON文件),配置文件,图标和图片(JPEG
,WebP
,GIF
,动画WebP
/ GIF
,PNG
,BMP
和WBMP
)。
指定 assets 目录
Flutter使用pubspec.yaml
文件(位于项目根目录),来识别应用程序所需的asset。
这里是一个例子:
flutter:
assets:
- assets/images/
- assets/fonts/
该assets
部分的flutter部分指定应包含在应用程序中的文件。 每个asset
都通过相对于pubspec.yaml
文件所在位置的显式路径进行标识。asset
的声明顺序是无关紧要的。asset
的实际目录可以是任意文件夹(在本示例中是assets
)。
加载字体
上面指定 assets/fonts/
目录加载字体文件夹,但并没有生效,需要添加 fonts
属性(下面展示添加字体和图片字体):
fonts:
- family: Montserrat
fonts:
- asset: assets/fonts/Montserrat-Light.ttf
weight: 300
- asset: assets/fonts/Montserrat-Regular.ttf
weight: 400
- asset: assets/fonts/Montserrat-Medium.ttf
weight: 500
- asset: assets/fonts/Montserrat-Bold.ttf
weight: 700
- family: customIcons
fonts:
- asset: assets/fonts/customIcons.ttf
使用
在代码中引入图片:
Padding(
padding: const EdgeInsets.only(bottom: 73),
child: Center(
child: Image.asset(
"assets/images/model.png",
width: double.infinity,
height: height * 0.7,
),
),
),
在代码中引入字体:
Text(
"\$208.99",
style: TextStyle(
color: Colors.red,
fontSize: ScreenUtil().setSp(36),
fontFamily: "Montserrat",
fontWeight: FontWeight.w700
),
)