Flutter https://flutter.cn/docs学习之添加资源和图片

https://flutter.cn/docs/development/ui/assets-and-images

Flutter 应用程序包含代码和 assets(也为资源)。资源是被打包到应用程序安装包中,可以在运行时访问的一种文件。常见的资源类型包括静态数据(例如 JSON 文件),配置文件,图标和图片(JPEG,WebP,GIF,动画 WebP / GIF,PNG,BMP 和 WBMP)

指定资源 Specifying assets  pubspec.yaml

flutter:
  assets:
    - assets/my_icon.png
    - assets/background.png

如果要包含一个目录下的所有 assets,需要在目录名称的结尾加上 /

flutter:
  assets:
    - directory/
    - directory/subdirectory/

  备忘

仅包含当前目录下的所有文件,以及子目录下(与主目录中的文件)的同名文件。(请参阅 Asset 变体)。如果想要添加子文件夹中的文件,请为每个目录创建一个条目。

=====>>>注释:::::: 如果与主目录中的文件名称不同名,,则 subdirectory 目录下的这个文件不会包含进去

资源打包

assets 部分的 flutter 部分需要指定包含在应用程序中的文件。每个资源都通过相对于 pubspec.yaml 文件所在位置的路径进行标识。资源的声明顺序是无关紧要的。资源的实际目录可以是任意文件夹(在第一个样例中是 assets,其他的是 directory

在一次构建中,Flutter 将 assets 放到 asset bundle 的特殊归档中,以便应用程序在运行时读取它们。

资源变体 Asset variants

前者被称为是 main asset,后者被称为是一种变体(variant

加载 assets

你的应用程序可以通过 AssetBundle 对象访问其资源。

Asset bundle 通过指定一个逻辑键(key),允许你读取 string/text(loadString)和 image/binary(load)。在编译期间,这个逻辑键(key)会映射在 pubspec.yaml 中指定的资源路径

加载文本 assets

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

但是,如果获取当前 BuildContextAssetBundle建议使用 DefaultAssetBundle这种方式不是使用应用程序构建的默认资源 bundle,而是让父级 widget 在运行时替换的不同的 AssetBundle,这对于本地化或测试场景很有用。

通常,你可以从应用程序运行时的 rootBundle 中,间接使用 DefaultAssetBundle.of() 来加载资源(例如 JSON 文件)。

在 Widget 上下文之外,或 AssetBundle 的句柄不可用时,你可以使用 rootBundle 直接加载这些 assets,例如:

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/config.json');
}

加载图片

Flutter 可以为当前设备加载适合其分辨率的图像。

pubspec.yaml 中资源部分的每一项都应与实际文件相对应,除过主资源节点。当主资源缺少某个文件时,会按分辨率从低到高的顺序去选择,也就是说 1x 中没有的话会在 2x 中找,2x 中还没有的话就在 3x 中找。该条目需要在 pubspec.yaml 中指定。

Widget build(BuildContext context) {
  return Image(image: AssetImage('graphics/background.png'));
}

  

依赖包中的资源图片

加载依赖 package 中的图像,必须给 AssetImage 提供 package 参数。

AssetImage('icons/heart.png', package: 'my_icons')

package 使用的本身的 Assets 也需要加上 package 参数来获取。  =======>注释::::自己写插件或者第三方插件,加载本身的 Assets 要加上 package 参数,否则会加载到主程序的Assets里

打包 assets

平台共享 assets     Sharing assets with the underlying platform

在 Android 平台上,assets 通过 AssetManager API 读取。通过 PluginRegistry.RegistrarlookupKeyForAsset 方法,或者 FlutterViewgetLookupKeyForAsset 方法来获取文件路径,然后 AssetManageropenFd 根据文件路径得到文件描述符。开发插件时可以使用 PluginRegistry.Registrar,而开发应用程序使用平台视图时,FlutterView 是最好的选择。

在 iOS 平台上,assets 资源文件通过 mainBundle 读取。通过 pathForResource:ofType:lookupKeyForAsset 或者 lookupKeyForAsset:fromPackage: 方法获取文件路径,同样,[FlutterViewController][] 的 lookupKeyForAsset: 或者 lookupKeyForAsset:fromPackage: 方法也可以获取文件路径。开发插件时可以使用 FlutterPluginRegistrar,而开发应用程序使用平台视图时, FlutterViewController 是最好的选择。

在 Flutter 中加载 iOS 的图片

平台 assets

 

posted on 2020-10-14 17:01  caosiqiao  阅读(297)  评论(0编辑  收藏  举报

导航