Dart中的库

关于Dart中的库

前面的内容基本上都是在一个文件里面编写Dart代码的,但实际开发中不可能这么写,模块化很重要,所以这就需要使用到库的概念。

在Dart中,库的使用时通过import关键字引入的。
library指令可以创建一个库,每个Dart文件都是一个库,即使没有使用library指令来指定。

分类

Dart中的库主要有三种:

dart中导入我们自定义的库

import 'lib/xxx.dart';

系统内置库

import 'dart:math';
import 'dart:io';
import 'dart:convert';

Pub包管理系统中的库

https://pub.dev/packages

https://pub.flutter-io.cn/packages

https://pub.dartlang.org/flutter/

引入流程:

1、需要在自己项目根目录新建一个pubspec.yaml

2、在pubspec.yaml文件 中配置名称 、描述、依赖等信息

3、然后运行 pub get 获取包下载到本地

4、项目中引入库 import ‘package:http/http.dart’ as http;

自定义库的使用

项目根目录定义Lib/Animal.dart

class Animal{
    
    
  String _name;   //私有属性
  int age; 
  //默认构造函数的简写
  Animal(this._name,this.age);

  void printInfo(){
    
       
    print("${this._name}----${this.age}");
  }

  String getName(){
    
     
    return this._name;
  } 
  void _run(){
    
    
    print('这是一个私有方法');
  }

  execRun(){
    
    
    this._run();  //类里面方法的相互调用
  }
}

main.dart引入刚才自定义的库

import 'lib/Animal.dart';
main(){
    
    
  var a=new Animal('小黑狗', 20);
  print(a.getName());
}

Dart系统内置库的使用

引入内置库直接使用

import "dart:math";

main() {
    
    
  print(min(12, 23));

  print(max(12, 25));
}

使用Pub包管理系统中的库

这一部分会在Flutter中进行简单说明。

猜你喜欢

转载自blog.csdn.net/weixin_41897680/article/details/125609206