When developing Flutter APK, we can preload some resources into APP. These resources can be divided into the following categories:

  • The text
  • The picture

For unified management, we put them in assets/ and then show you how to read them.

A, text,

Text is generally used to store default data and display data when entering the net for the first time.

Yaml, under the flutter TAB, declare the file name to load:

flutter:

  assets :
    - assets/files/hello.txt
Copy the code

Text can be loaded in two ways:

  • Use global staticrootBundleObject that needs to be importedpackage:flutter/services.dartThe advantage is that you don’t need to provideBuildContext.
  • useDefaultAssetBundleGets the currentBuildContexttheAssetBundleTo load.

Example code for both methods is as follows, corresponding to _loadAssetFile() and _loadAssetFile2() :

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(AssetDemo());

class AssetDemo extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Assets Demo')), body: AssetFilesWidget(), ), ); }}class AssetFilesWidget extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return_AssetFilesWidgetState(); }}class _AssetFilesWidgetState extends State<AssetFilesWidget> {

  String text;

  @override
  void initState() {
    super.initState();
    _loadAssetFile2();
  }

  @override
  Widget build(BuildContext context) {
    return Text(text ?? 'default');
  }

  _loadAssetFile() async {
    String text = await rootBundle.loadString('assets/files/hello.txt');
    print(text);
    setState(() {
      this.text = text;
    });
  }

  _loadAssetFile2() async {
    String text = await DefaultAssetBundle.of(context).loadString('assets/files/hello.txt');
    setState(() {
      this.text = text; }); }}Copy the code

Second, the picture

Images are similar to text in that they need to be declared before being used.

On Android, we put the image under res/ with the corresponding drawable-? Folders. Images loaded into memory are of different sizes depending on the device DPI (number of dots per inch). A similar concept applies to Flutter.

For more information on the relevant concepts in Android, see this article.

In Flutter, there is also the drawable-? Same design, use N.X instead:

The loading logic is as follows:

  • The root directory default corresponds to1.0Resolution image.
  • When the device selects an image, it will select away from itdpiDensityThe most recent folder. ifDpiDensity = 1.8, then will choose2.0 xResources in the directory. (dpiDensitywithMediaQuery.of(context).devicePixelRatioTo get.)
  • Determine which folder of images to select, if not setImage WidgetControl, so the width of the final load display should be the width of the original image divided by the coefficient of the corresponding folder.

The following is an example: declare in pubspec.yaml:

flutter:

  uses-material-design: true

  assets :
    - assets/files/hello.txt
    - assets/images/
Copy the code

Load the Image with Image(key: imageKey, Image: AssetImage(‘assets/images/pic.png’)).

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(AssetDemo());

class AssetDemo extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Assets Demo')), body: AssetImageWidget(), ), ); }}class AssetImageWidget extends StatefulWidget {
  
  @override
  State<StatefulWidget> createState() {
    return_AssetImageWidgetState(); }}class _AssetImageWidgetState extends State<AssetImageWidget> {
  
  String text;
  GlobalKey imageKey = new GlobalKey();
  
  @override
  Widget build(BuildContext context) {
    return Column(children: <Widget>[
      RaisedButton(onPressed: () {
        text = 'height=${imageKey.currentContext.size.height}'
            ',width=${imageKey.currentContext.size.height}'
            ',dpi=${MediaQuery.of(context).devicePixelRatio}';
        print(text);
      }, child: Text('refresh')),
      Image(key : imageKey, image : AssetImage('assets/images/pic.png'))); }}Copy the code

To verify the previous loading logic, the following three cases were tested:

  • In the main resourcesassets/imagesAdd to directorypic.png, the result is:
height=96.0,width=96.0,dpi=3.0
Copy the code
  • In the main resource andAssets/images / 3.0 xAdd to directorypic.png, the result is:
height=32.0,width=32.0,dpi=3.0
Copy the code
  • In the main resource andAssets/images / 2.0 xAdd to directorypic.png, the result is:
height=48.0,width=48.0,dpi=3.0
Copy the code

A bit of note here is that when we change the structure of the resource directory, we need to modify pubspec.yaml to take effect.

3. Use images from third-party packages

3.1 The application uses images from third-party packages

When an application depends on a package named my_icons, the images are loaded as follows:

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

3.2 Packaging third-party images

There are several situations for images in third-party packages:

  • Third party packages use their own resources, then must be in its ownpubspec.yaml, and use it with your own package name.
  • The third-party package is provided to other people but not used by itself, which can be divided into two situations:
    • Force packaging whether the consumer uses it or not. In this case, the third party package needs to be in itpubspec.yamlThe user does not.
    • It is up to the user to choose whether to pack. Third-party packages place resources onlib/Directory and not inpubspec.yamlDeclaration by the user based on usage in its ownpubspec.yamlIn a statement.

For example, a third-party pack named Fancy_Wallpapers provides:

... / lib/backgrounds/background1. PNG... / lib/backgrounds/background2. PNG... /lib/backgrounds/background3.pngCopy the code

If the user wishes to use Background1, it declares it in its own pubspec.yaml, noting that the implicit lib directory is omitted:

flutter:
  assets:
    - packages/fancy_backgrounds/backgrounds/background1.png
Copy the code

Refer to the article

  • Add resources and images to Flutter
  • (2) analysis of memory occupied by Bitmap