Flutter 笔记 之 依赖包管理

在Flutter中,依赖包由 Pub 仓库管理,项目依赖配置在pubspec.yaml文件中声明即可(类似于NPM的版本声明 Pub Versioning Philosophy ),对于未发布在Pub仓库的插件可以使用git仓库地址或文件路径:

dependencies: 
  url_launcher: ">=0.1.2 <0.2.0"
  collection: "^0.1.2"
  plugin1: 
    git: 
      url: "git://github.com/flutter/plugin1.git"
  plugin2: 
    path: ../plugin2/

以shared_preferences为例,在pubspec中添加代码:

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "^0.4.1"

脱字号“^”开头的版本表示 和当前版本接口保持兼容 的最新版,^1.2.3 等效于 >=1.2.3 <2.0.0而 ^0.1.2 等效于 >=0.1.2 <0.2.0,添加依赖后点击“Packages get”按钮即可下载插件到本地,在代码中添加import语句就可以使用插件提供的接口:

import 'package:shared_preferences/shared_preferences.Dart';
class _MyAppState extends State {
  int _count = 0;
  static const String COUNTER_KEY = 'counter';
  _MyAppState() {
    init();
  }
  init() async {
    var pref = await SharedPreferences.getInstance();
    _count = pref.getInt(COUNTER_KEY) ?? 0;
    setState(() {});
  }
  increaseCounter() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setInt(COUNTER_KEY, ++_count);
    setState(() {});
  }
...

你可能感兴趣的:(Flutter-笔记)