Flutter: Resource Management Summary

1. Import three-party dependencies:

(1) Add three-party dependencies, in pubspec.yaml:

name: APP名称
description: APP描述
version: 1.0.0+1   #版本号
dependencies:  #生产环境依赖包,等同Android端build.gradle中的dependencies
  flutter:   #例:依赖flutter
    sdk: flutter
  三方依赖名称: ^0.0.0   #三方依赖版本号
dev_dependencies:  #开发环境依赖包,等同Android端build.gradle中的dependencies
  flutter_test:   #例:依赖flutter
    sdk: flutter
  三方依赖名称: ^0.0.0   #三方依赖版本号
flutter:    #flutter相关的配置选项
  uses-material-design: true  #可以使用material design

(2) Pull the three-party dependency package:

After Android Studio opens the pubspec.yaml file, click "Pub get" in the upper right corner to pull the three-party dependency package.

2. Import pictures and other resources:

(1) Configure resource paths such as pictures, in pubspec.yaml:

flutter:
  assets:  #配置资源
    - 目录名/my_icon.png   #某张图片路径,目录名如images

(2) Use resources such as pictures:
load text:

import 'package:flutter/services.dart' show rootBundle;
...
rootBundle.loadString('目录名/文件名.json');
DefaultAssetBundle.of().loadString('目录名/文件名.json');

Load image:

ImageProvider imgP = AssetImage('目录名/图片名.png');
Widget imgW = Image.asset('目录名/图片名.png');

3. Color and theme:

(1) Color:

Common methods of Color:

Color color = Color(int.parse("ffffff", radix:16) | 0xFF000000);   //通过位运算符方式转换为Color
Color color = Color(int.parse("ffffff", radix:16)).withAlpha(255); //通过API方法转换为Color
double 亮度值 = color.computeLuminance();                          //亮度值[0-1],值越大颜色越浅

Common methods of MaterialColor:

Colors.red.shade50;    //获取某个颜色从浅到深的渐变色值(shade为50-900)
Colors.red.shade100; 
Colors.red.shade200; 
...
Colors.red.shade900;

(2) Use themes:

Theme( //Theme也是Widget
  data: ThemeData( //主题
    primarySwatch: Colors.blue, //配置导航栏/loatingActionButton背景色
    iconTheme: IconThemeData(color: color值), //配置Icon默认样式
    dialogBackgroundColor: color值,    //dialog默认默认背景色
    scaffoldBackgroundColor: color值,  //Scaffold默认背景色
    //...等等
  ),
  child: ...,  //省略具体页面布局
)

4. Use internationalization:

(1) Add the internationalization dependency of the Intl package, in pubspec.yaml:

dependencies:
  intl: ^0.17.0   #引用和加载intl_generator生成后的dart代码
...
dev_dependencies:
  intl_generator:  0.2.1   #开发阶段从代码中提取文本到单独的arb文件、根据arb文件生成对应语言的dart代码
...

(2) Create the l10n-arb folder in the project root directory, and create the l10n folder in the project lib directory:

l10n-arb:存放使用intl_generator命令生成的arb文件
lib\l10n:存放从arb文件生成的dart代码文件

(3) Implement the string definition class and the Locale proxy class:

<1> String definition class, in which all string fields that need to be internationalized are defined:

class StringDef {//字符串定义类,在此类中定义所有需要国际化的字符串字段
  static Future<StringDef> load(Locale locale) {
    final String name = locale.countryCode!.isEmpty ? locale.languageCode : locale.toString();
    final String localeName = Intl.canonicalizedLocale(name);
    return initializeMessages(localeName).then((b) { //执行第(6)步命令后,initializeMessages方法才不会报错
      Intl.defaultLocale = localeName;
      return StringDef();
    });
  }
  static StringDef of(BuildContext context) {
    return Localizations.of<StringDef>(context, StringDef)!;
  }
  String get app_name { //需要国际化的字符串字段名
    return Intl.message(
      'heartknow',  //需要国际化的字符串字段值
      name: 'app_name',
      desc: '...',
    );
  }
  String get home_title { //需要国际化的字符串字段名
    return Intl.message(
      'home title',  //需要国际化的字符串字段值
      name: 'home_title',
      desc: '...',
    );
  }
  //...省略其他字符串字段
}

<2>Locale proxy class:

class MyLocalizationsDelegate extends LocalizationsDelegate<StringDef> {//Locale代理类
  const MyLocalizationsDelegate();
  @override
  bool isSupported(Locale locale) => ['en', 'zh'].contains(locale.languageCode); //支持的语言列表
  @override
  Future<StringDef> load(Locale locale) { //系统会调此方法加载Locale资源类
    return StringDef.load(locale);
  }
  @override
  bool shouldReload(MyLocalizationsDelegate old) => false; //重新build时,是否调用load重新加载Locale资源.
}

(4) Generate the intl_messages.arb file according to StringDef.dart (cd in cmd to the root directory of the project and execute the following command):

D:\workspace\flutter_demo> flutter pub pub run intl_generator:extract_to_arb --output-dir=l10n-arb \ lib/l10n/StringDef.dart

The intl_messages.arb file will be generated in the project/110n-arb directory (supports English language):

{
  "@@last_modified": "2022-10-25T14:40:33.848464",
  "app_name": "heartknow",  //需要国际化的字段1
  "@app_name": {
    "description": "...",
    "type": "text",
    "placeholders_order": [],
    "placeholders": {}
  },
  "home_title": "home title",  //需要国际化的字段2
  "@home_title": {
    "description": "...",
    "type": "text",
    "placeholders_order": [],
    "placeholders": {}
  }
}

(5) Copy and rename the intl_messages.arb file to intl_zh_CN.arb (support Chinese language), the content is as follows:

{
  "@@last_modified": "2022-10-25T14:40:33.848464",
  "app_name": "心知了",  //需要国际化的字段1
  "@app_name": {
    "description": "...",
    "type": "text",
    "placeholders_order": [],
    "placeholders": {}
  },
  "home_title": "首页标题",  //需要国际化的字段2
  "@home_title": {
    "description": "...",
    "type": "text",
    "placeholders_order": [],
    "placeholders": {}
  }
}

(6) Generate messages_all.dart and messages_messages.dart files according to intl_messages.arb (cd in cmd to the root directory of the project and execute the following commands):

D:\workspace\flutter_demo> flutter pub pub run intl_generator:generate_from_arb --output-dir=lib/l10n --no-use-deferred-loading lib/l10n/StringDef.dart l10n-arb/intl_messages.arb

(7) Use internationalized string fields:

String homeTitle = StringDef.of(context).home_title; //使用StringDef中定义的国际化字符串字段


 

Guess you like

Origin blog.csdn.net/a526001650a/article/details/127514352