dart基础类型与方法使用

dart基础类型与方法使用

类型及方法

  • 字符串、数字、列表、集合、映射,及列表、集合、映射相互转换
void foo() {
  var toly = Person('xiaoming');
  toly.say();
  var bm = toly.bmi(height: 170, weight: 60);
  print(bm);
  toly.logNumFunc(-100.5);
  toly.logStrFunc('你好.abdfd   ');
  toly.logListFun(['1']);
  toly.logSetFun({'0'});
  toly.logMapFun({'a': 1});
  toly.logListToSet();
}

class Person {
  final String name; // 声明语句
  Person(this.name); // 方法
  void say() {
    print('我是' + this.name);
    // 运行时的类型
    print(this.name.runtimeType);
  }

  double bmi({required double height, required double weight}) {
    return weight / (height * height);
  }

  logNumFunc(double num) {
    print('abs:' + num.abs().toString());
    print('ceil:' + num.ceil().toString());
    print('floor:' + num.floor().toString());
    print('四舍五入round:' + num.round().toString());
    print('去除小数取整truncate:' + num.truncate().toString());
    print('四舍五入,保留几位小数toStringAsFixed:' + num.toStringAsFixed(2).toString());
    print('double 通过解析数据获得数字:' + double.parse(num.toString()).toString());
    print('int 通过解析数据获得数字:' + int.parse('10').toString());
    print('将十进制转为2进制:' + num.ceil().toRadixString(2).toString());
  }

  void logStrFunc(String str) {
    print('字符串模板:${str}');
    print('字符串索引值获取字符:' + str[1]);
    print('获取字符串长度:' + str.length.toString());
    print('字符串截取:' + str.substring(2));
    print('去掉首位空格trim():' + str.trim());
    print('去掉左边空格:' + str.trimLeft());
    print('去掉右边空格:' + str.trimRight());
    print('字符串小写:' + str.toLowerCase());
    print('字符串大写:' + str.toUpperCase());
    print('字符串startsWith:' + str.startsWith('1212').toString());
    print('字符串endsWith:' + str.endsWith('1212').toString());
    print('字符串contains:' + str.contains('a').toString());
    print('字符串replaceAll :' + str.replaceAll('a', '_A'));
    print('字符串split :' + str.split('').toString());
  }

  // 聚合类型:List Map Set 列表 映射 集合
  logListFun(List<String> list) {
    list.add('张三');
    list.addAll(['a', 'b', 'c', 'd']);
    list.insert(1, '88');
    list.insertAll(2, ['66', '77']);
    list.removeAt(0);
    list.remove('77');
    print(
        '列表List新增add:|多个新增addAll:|指定位置新增insert:|指定位置多个新增insertAll|删除指定位置的值removeAt:|删除某个元素remove:' +
            list.toString());
    list[6] = '00';
    print('List通过索引直接修改或者访问某个值:' + list[2]);
  }

  logSetFun(Set set) {
    set.add('张三');
    set.addAll(['a', 'b', 'c', 'd']);
    set.remove('77');
    set.removeAll(['a', 'b']);
    set.add('0'); // 重复新增无效
    Set set2 = {'a', 'b', 'c', 'd'};
    print('集合Set没有索引值,新增add/addAll  remove/removeAll' + set.toString());
    print('Set交集intersection:' + set.intersection(set2).toString());
    print('Set补集difference:' + set.difference(set2).toString());
  }

  logMapFun(Map<String, int> map) {
    print('map通过key值访问,如果不存在就是添加:' + map['b'].toString());
    map['c'] = 3;
    map['d'] = 4;
    print('map通过remove key删除:' + map.remove('c').toString());
  }

  logListToSet() {
    List<String> list = ['a', 'b', 'c', 'd', 'a'];
    Set<String> set = list.toSet();
    List<String> list1 = set.toList();
    List<String> list3 = ['a', 'b', 'c'];
    Set set1 = {0, 1, 2};
    Map map = Map.fromIterables(set1, list3);
    print('通过toSet ,toList方法去重' + list1.toString());
    print('通过asMap将list转换为map' + list1.asMap().toString());
    print('Map通过fromIterables可以将set list转为map对象 ' + map.toString());
    print('Map的keys方法: ' + map.keys.toString());
    print('Map的values方法: ' + map.values.toString());
    print('Map的keys方法可以用toSet toList转为Set list: ' +
        map.values.toList().toString());
  }
}

void main() {
  foo();
}

自定义异常

int test1(int num) {
  if (num < 100) {
    throw Exception("${num} is not a valid number");
  }
  return num;
}
class MyException implements Exception {
  final String args;

  MyException(this.args);

  
  String toString() => '入参${this.args}不能为空';
}

void main() {
  try {
    test1(1);
  } on MyException catch (a) {
    print(a);
  } catch (e, s) {
    print('异常对象' + e.toString());
    print('异常追踪信息' + s.toString());
  } finally {
    print('无论是否有异常,都会执行');
  }
  print('this is a test');
}

运算符

void calculate({required int number1, required int number2}) {
  print('或者数字${number1} 和 数字${number2} 的商,用~/:' +
      (number1 ~/ number2).toString());
}

void caseFun(num1, num2, param1) {
  print('!=两个是否相等:' + (param1 != null).toString());
  if (num1 > num2) {
    print('大于');
  } else if (num1 == num2) {
    print('等于');
  } else {
    print('小于');
  }
}

void evalFun(a) {
  var b = a ??= 20; // 如果a为null,将20赋值给b
  print(b);
  print(b &= 10);
  print(b |= 10);
}

void main() {
  calculate(number1: 10, number2: 3);
  caseFun(1, 2, '');
  evalFun(null);
}

class类

class Test {
  double x, y; // 成员变量
  String? _name;
  Test(this.x, this.y); // 构造方法,用于对成员变量进行赋值,this.x =x; this.y =y;
  void add() {
    //成员方法
    print(x + y);
  }

  // get关键字,使用之后可以不加()
  double get area => x * y;
  // 等价于如下
  double getArea() => x * y;
  // set关键字,使用之后可以不加()
  void set name(String? value) {
    if (value != null) {
      _name = value;
    } else {
      _name = '';
    }
    print('name = ${_name}');
  }
}

class Student {
  Document document;

  Student(this.document);

  void event(String string) {
    document.records.add(string);
  }

  String callDocument() {
    return document.records.join("\n");
  }

  void died() {
    document.records.clear();
  }
}

class Document {
  List<String> records = [];

  void addRecord(String string) {
    records.add(string);
  }
}

void main() {
  Test t = new Test(1, 2);
  t.x = 100;
  t.name = '3232';
  print(t.x);
  print(t.area);
  print(t.area);
  Document document = new Document();
  Student xiaoming = new Student(document);
  xiaoming.event('xiaoming2001年幼儿园');
  xiaoming.event('xiaoming2004年小学');
  xiaoming.event('xiaoming2011年初中');
  String res = xiaoming.callDocument();
  print(res);
}

抽象类

  • 继承
// 此处类 当接口用
class Vec2 {
  int x;
  int y;
  Vec2(this.x, this.y);
}

abstract class Shape {
  Vec2 center;
  Shape(this.center);
  void move() {
    center.x += 10;
    center.y += 10;
  }

  void draw() {
    String info = '绘制矩形:中心点(${this.center.x}${this.center.y}${drawChildIn()}';
    print(info);
  }

  String drawChildIn();
}

class Rectangle extends Shape {
  double height;
  double width;
  Rectangle(Vec2 center, {this.height = 10, this.width = 10}) : super(center);
  
  String drawChildIn() {
    return '高:${this.height},宽:${this.width}';
  }
}

void main() {
  Rectangle rectangle = Rectangle(Vec2(100, 100));
  rectangle.draw();
  rectangle.move();
}

接口实现

必须强制覆写 所有 成员方法
必须 强制覆为 所有 成员变量提供 get 方法

class A {
  String name;
  A(this.name);
  log() {
    print(this.name);
  }
}

class B {
  String name;
  B(this.name);
  log() {
    print(this.name);
  }
}

class C implements A, B {
  // @override
  // String get name => 'C';

  // @override
  // set name(String _name) {
  //   this.name = _name;
  // }
  
  String name;
  int age;
  C(this.name, this.age);
  log() {
    print('${this.name} is ${this.age} years old');
  }
}

void main() {
  C c = C('张三', 20);
  c.log();
}

混入类

定义的抽象方法 要求派生类必须实现 抽象方法
混入类不能拥有【构造方法】
二义性问题时,会 “后来居上"

mixin MoveAble {
  double speed = 20;
  void move() {
    print('===$runtimeType==');
  }

  void log();
}
// 两个混入类可以通过on 继承
mixin Position on MoveAble {
  double x = 0;
  double y = 0;
}

// 因为 Position继承了 MoveAble, 应该先混入MoveAble
class Shap with MoveAble, Position {
  
  void log() {
    print('===log==');
  }
}

void main() {
  Shap a = new Shap();
  a.speed = 100;
  a.move();
  a.log();
  print(a is MoveAble);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值