在 dart 中,库的使用,是通过 import 关键字引入的。

library 指令可以创建一个库,每个 dart 文件都是一个库,即使没有使用 library 指令来指定。

dart 中的库主要有三种:

  1. 我们自定义的库
    import 'lib/xxx.dart';
  2. 系统内置库
    import 'dart:math';
    import 'dart:io';
    import 'dart:convert';
  3. 第三方库(Pub 包管理系统中的库)
    import 'package:http/http.dart' as http

第三方库的使用:
1、在项目根目录新建一个 pubspec.yaml
2、配置 pubspec.yaml,包含配置名称、描述、依赖等信息
3、获取包,运行 pub get 将包下载到本地
4、项目中引入,如 import 'package:http/http.dart' as http

引入第三方库

  1. 从官方网址找到要用的库
    https://pub.dev/packages
    https://pub.flutter-io.cn/packages
    https://pub.dartlang.org/flutter/

  2. 创建一个 pubspec.yaml 文件,格式如下:

    name: xxx
    descripition: A new flutter module project.
    dependencies:
      http: ^0.12.0+2
      date_format: ^1.0.6
    
  3. 配置 dependencies

  4. 运行 pub get 获取远程库

  5. 查看引入的第三方库使用文档

     import 'dart:convert' as convert;
     import 'package:http/http.dart' as http;
    
     void main(List<String> arguments) async {
     // This example uses the Google Books API to search for books about http.
     // https://developers.google.com/books/docs/overview
     var url =
         Uri.https('www.googleapis.com', '/books/v1/volumes', {'q': '{http}'});
    
     // Await the http get response, then decode the json-formatted response.
     var response = await http.get(url);
     if (response.statusCode == 200) {
         var jsonResponse =
             convert.jsonDecode(response.body) as Map<String, dynamic>;
         var itemCount = jsonResponse['totalItems'];
         print('Number of books about http: $itemCount.');
     } else {
         print('Request failed with status: ${response.statusCode}.');
     }
     }
    

async await

这两个关键字的使用只需要记住两点:
1、只有 async 方法才能使用 await 关键字调用方法
2、如果调用别的 async 方法必须使用 await 关键字

async 是让方法变成异步。

await 是等待异步方法执行完成。

void main() async {
    var result = await testAsync();
    print(result);
}

// 异步方法
testAsync() async{
    return 'Hello async';
}

库冲突处理

当引入两个库中有相同名称标识符的时候,如果是 java 通常我们通过写上完整包命名路径来指定,在 dart 中则是通过 as 关键字来解决,即重命名。

import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;

部分导入

如果只需导入库的一部分,有两种模式:

  • 模式 1:只导入需要的部分,使用 show 关键字,如 import 'package:lib1/lib1.dart' show foo;
  • 模式 2:隐藏不需要的部分,使用 hide 关键字,如 import 'package:lib2/lib2.dart' hide foo;

延迟加载

也称为懒加载,可以在需要的时候再进行加载。
懒加载最大的好处是可以减少 APP 的启动时间。

懒加载使用 deferred as 关键字来指定,如 import 'package:deferred/hello.dart' deferred as hello;

当需要的时候,需要使用 loadLibrary()方法来加载:

greet() async{
    await hello.loadLibrary();
    hello.printGreeting();
}
posted @ 2025-10-18 12:06  505donkey  阅读(21)  评论(0)    收藏  举报