周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. dart
  3. 正文

dart 使用part、part of、library拆分库

2024年 4月 26日 1109点热度 0人点赞 0条评论
  • dart中,通过使用part、part of、library来实现拆分库,这样,就可以将一个庞大的库拆分成各种小库,只要引用主库即可,用法如下:

  • 假设有三个文件,两个子库calculator和logger,一个主库util

    • calculator.dart
    // 和主库建立连接
    part of util;
    
    int add(int i, int j) {
      return i + j;
    }
    
    int sub(int i, int j) {
      return i - j;
    }
    
    int random(int no) {
      return Random().nextInt(no);
    }
    
    int _info(int i, int j) {
      return i + j;
    }
    • logger.dart
    // 和主库建立连接
    part of util;
    
    class Logger {
      String _app_name;
      Logger(this._app_name);
      void error(error) {
        print('${_app_name} Error: ${error}');
      }
    
      void warn(msg) {
        print('${_app_name} Warn:${msg}');
      }
    
      void debug(msg) {
        print('${_app_name} debug:${msg}');
        // 依赖库之间  私有方法可以调用,外部无法调用
        _info(10, 20);
      }
    }
    • util.dart
    // 库命名
    library util;
    
    // 导入math,子库用到
    import "dart:math";
    
    // 和子库建立连接
    part 'calculator.dart';
    part 'logger.dart';
  • 使用:main.dart

    import './util.dart';
    
    void main() {
    // 使用logger库定义的类
    Logger logger = Logger("Demo");
    logger.debug("测试debug");
    logger.warn("测试警告");
    
    // 使用calculator库的方法
    print(add(1, 2));
    print(sub(4, 10));
    }

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2024年 4月 26日

周凯

这个人很懒,什么都没留下

打赏 点赞

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号