math 库的使用

import 'dart:math';

void main() {
    // 最大和最小值
    assert(max(1, 1000) == 1000);
    assert(min(1, -1000) == -1000);

    // 数学常量
    print(e); // 2.718281828459045
    print(pi); // 3.141592653589793
    print(sqrt2); // 1.4142135623730951
}

随机数

import 'dart:math';  

void main() {
  var random = Random();
  print(random.nextDouble()); // 介于 0.0 ~ 1.0: [0, 1)
  print(random.nextInt(10));  // 介于 0 ~ 9 : [0, 9)
  print(random.nextBool());   // 生成随机布尔值
}

还可用于列表的shuffle方法中

import 'dart:math';

void main() {
  var names = ["zhangsan","lisi","lee","burce"];
  print(names);
  // 随机打乱列表顺序
  names.shuffle(Random());
  print(names);
}

JSON 编解码

Dart 提供了dart:convert库直接用于JSON字符串的编解码

import 'dart:convert';

var scores = [
  {'score': 40},
  {'score': 80},
  {'score': 100, 'overtime': true, 'special_guest': null}
];

void main() {
    // jsonEncode函数将Dart的List或Map对象编码为json格式的字符串
    var jsonText = jsonEncode(scores);
    assert(jsonText ==
        '[{"score":40},{"score":80},'
        '{"score":100,"overtime":true,'
        '"special_guest":null}]');

    // jsonDecode 函数将json格式的字符串解码为Dart的List或Map对象
    var scores = jsonDecode(jsonString);
    assert(scores is List);
}

字符串的编解码

dart:convert还可用于字符串的编解码,即Java中的字符串与字节数组的相互转换。

void main() {
  // 用utf8编码将字符串转换为字节数组
  List<int> utf8Bytes = utf8.encode('Dart编程指南');
  print(utf8Bytes);

  // 将utf8编码的字节数组转为字符串
  String text = utf8.decode(utf8Bytes);
  print(text);
}

注意,Dart默认使用utf-8编码,dart:convert库另外还提供了ASCII和ISO-8859-1 (Latin1)转换器,如需处理GBK编码,需要使用第三方库进行转换。

Dart 2.7 新特性

扩展方法(Extension methods)

Dart 2.7 添加了一个强大的新特性:扩展方法。它使你可以向任何类型添加新功能,并具有常规方法调用的简洁性。当我们在使用某些SDK中的类时,由于无法修改类的源码,导致我们不能扩展该类,这个特性就很好的解决了这种情况。

extension <extension name> on <type> {
  (<member definition>)*
}

代码示例

extension SplitChar on String {
    List<String> toList(){
    return this.split('');
    }
}

void main() {
  // 1.直接使用: [a, b, c, d, e, f]
  print("abcdef".toList());

  // 2.使用包装类: [a, b, c, d, e, f]
  print(SplitChar("abcdef").toList());
}

安全子字符串

需要使用一个第三方库 characters

var input = ['Resume', 'Résumé', '이력서', '💼📃', 'Currículo'];
input.forEach((s) => print(s.substring(0, 3)));
input.forEach((s) => print(s.characters.take(3)));

公众号“编程之路从0到1”

20190301102949549

Copyright © Arcticfox 2020 all right reserved,powered by Gitbook文档修订于: 2024-06-09 20:22:55

results matching ""

    No results matching ""