Flutter添加资源和图片

2022/11/25 Flutter静态资源

本文介绍Flutter项目如何添加静态资源和图片,并且如何规范的创建文件目录和导入资源。

# 加入资源

  • 编辑pubspec.yaml,在根目录下创建asssets,然后按资源类型,分别创建目录;
    # The following section is specific to Flutter.
    flutter:
      ...
    
      # To add assets to your application, add an assets section, like this:
      assets:
        - assets/images/
        - assets/svgs/
        - assets/json/
    
    1
    2
    3
    4
    5
    6
    7
    8
    9

# 加入图片

  • lib下创建assets.dart,将静态资源导出;
    class AssetImages {
      static const bykJpg = 'assets/images/byk.jpg';
    }
    
    1
    2
    3

# 使用

  • 示例
    import 'package:flutter/material.dart';
    import 'package:flutter_application_1/assets.dart';
    
    void main(List<String> args) {
      runApp(const ModelBox());
    }
    
    class ModelBox extends StatelessWidget {
      const ModelBox({Key? key}) : super(key: key);
    
      
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: const Text('Box Model'),
            ),
            body: Center(
              widthFactor: 2,
              heightFactor: 2,
              child: Image.asset(AssetImages.bykJpg)
            )
          ),
        );
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
最后更新时间: 2022/11/29 07:33:47