Flutter 中添加静态资源

作者: 皱巴巴 | 来源:发表于2018-10-10 18:10 被阅读86次

    一个应用程序少不了一些静态资源,例如:图片、字体、配置文件等。这些静态资源会打包到程序安装包中,可以在运行时访问。
    Flutter 中添加静态资源很简单,将静态资源放置在任意目录(通常是根目录下的 assets 文件夹中),然后在配置文件中 pubspec.yaml 中指定即可。每个 asset 都通过相对于 pubspec.yaml 文件所在位置的路径进行标识。asset 的声明顺序是无关紧要的。
    在构建期间,Flutter 将 asset 放置到称为 asset bundle 的特殊存档中,应用程序可以在运行时通过 AssetBundle 对象访问。

    查看示例代码

    assets.png

    加载文本

    每个 Flutter 应用程序都有一个 rootBundle 对象, 可以轻松访问主资源包,也可以直接使用 package:flutter/services.dart 中全局静态的rootBundle 对象来加载 asset。

    但是,建议使用 DefaultAssetBundle.of 来获取当前 BuildContext 的 AssetBundle。这种方法不是使用应用程序构建的默认 asset bundle,而是使父级 widget 在运行时替换的不同的 AssetBundle ,这在本地化或测试时很有用。

    接下来以读取本地 JSON 文件为例进行说明。

    创建 assets/person.json 文件,并写入以下内容:

    [
      {
        "name": "Tom",
        "age": 23,
        "height": 172,
        "gender": "male"
      },
      {
        "name": "Jerry",
        "age": 18,
        "height": 163,
        "gender": "male"
      },
      {
        "name": "Lina",
        "age": 30,
        "height": 180,
        "gender": "female"
      }
    ]
    

    pubspec.yaml 中配置资源:

    flutter:
      assets:
        - assets/person.json
    

    接着,创建一个页面,用来展示 JSON 数据:

    import 'dart:convert' show json;
    
    import 'package:flutter/material.dart';
    
    class Assets extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text('Assets'),
          ),
          body: new JsonView(),
        );
      }
    }
    
    class JsonView extends StatefulWidget {
      @override
      State<StatefulWidget> createState() {
        return new _JsonViewState();
      }
    }
    
    class _JsonViewState extends State<JsonView> {
      @override
      Widget build(BuildContext context) {
        return new FutureBuilder(
          future: DefaultAssetBundle.of(context).loadString("assets/person.json"),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              List<dynamic> data = json.decode(snapshot.data.toString());
    
              return new ListView.builder(
                itemCount: data.length,
                itemBuilder: (BuildContext context, int index) {
                  return new Card(
                    child: new Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: <Widget>[
                        new Text("Name: ${data[index]["name"]}"),
                        new Text("Age: ${data[index]["age"]}"),
                        new Text("Height: ${data[index]["height"]}"),
                        new Text("Gender: ${data[index]["gender"]}"),
                      ],
                    ),
                  );
                },
              );
            }
            return new CircularProgressIndicator();
          },
        );
      }
    }
    

    这里主要使用了 DefaultAssetBundle.of() 获取 AssetBundle,然后使用 FutureBuilder 组件显示异步数据。

    加载图片

    Flutter 中使用 AssetImage 组件展示图片。Flutter 会根据当前设备的分辨率加载对应的图片,我们只需要按照特定的目录结构来放置图片,例如:

    assets
    ├── images
        ├── wechat.png
        ├── 2.0x
            ├── wechat.png
        ├── 3.0x
            ├── wechat.png
    

    使用时:

    new Image.asset("assets/images/wechat.png")
    
    // or
    new Image(
      image: new AssetImage("assets/images/wechat.png"),
    ),
    

    加载字体

    下载字体并在 pubspec.yaml 中配置,这里的配置方式和前面有一点区别:

    fonts:
      - family: Charmonman
        fonts:
          - asset: assets/fonts/Charmonman-Regular.ttf
          - asset: assets/fonts/Charmonman-Bold.ttf
            weight: 500
    

    其中 weight 属性指定字体的粗细,对应 TextStylefontWeight 属性,会匹配对应的字体。同理还有 style 属性,对应的值为 italicnormal

    使用时,通过 TextStyle 指定对应的字体即可:

    new Text(
      "A red flair silhouetted the jagged edge of a wing.",
      style: new TextStyle(
        fontFamily: "Charmonman",
        fontSize: 17.0,
        fontWeight: FontWeight.w500,
      ),
    )
    

    使用字体图标

    字体图标的使用和普通字体使用没太大区别,只是文本内容使用对应图标的 Unicode 码点即可:

    new Text(
      "\u{e7d7}",
      style: new TextStyle(
        fontFamily: "Iconfont",
        fontSize: 36.0,
      ),
    ),
    

    相关文章

      网友评论

        本文标题:Flutter 中添加静态资源

        本文链接:https://www.haomeiwen.com/subject/pgrmaftx.html