美文网首页
Dart基础

Dart基础

作者: PaulLuv | 来源:发表于2018-03-03 17:07 被阅读508次

Java to Dart

String是不可变的,一旦定义就不能改变。

Immutable

String are immutable objects, which means you can create them but you can't change them. You can of course build a new string out of other strings, but once created, the string's contents are fixed.

This is an optimization, as two strings with the same characters in the same order can be the same object.

var s11 = "strings are immutable";
var s21 = "strings are immutable";

print(s11 == s21); // true, contain the same characters
print(identical(s11, s21)); // true, are the same object in memory

StringBuffer是可改变的,定义后还可以再修改

StringBuffer xiaomingSaid = new StringBuffer();
xiaomingSaid.write("All the world's a stage ... ");
xiaomingSaid.write("And all the men and women merely players ...");
print(xiaomingSaid);

StringBuffer strBuf = new StringBuffer();
// 添加字符串到字符串缓冲区内
strBuf.write("Do one thing at a time, and do well.");
// 返回字符串缓冲区的所有内容
print(strBuf.toString());
// 清除字符串缓冲区
strBuf.clear();

Dart 集合 -List,Map,Set

List

List有固定长度的,一旦定义就无法改变长度。有可变长度的,可以根据需要改变长度。

List([int length])

// 创建固定长度的列表  
List fixedLengthList = new List(3);  

// 创建可改变长度的列表  
List growableList = new List();  
growableList.length = 3;  

// 创建可在固定范围内改变长度的列表  
List growableListB = new List()..length = 500;  

List.unmodifiable(Iterable elements)

// 创建包含所有元素的固定长度列表  
List fixedLengthListB = new List.unmodifiable([1,2,3]);

List.from(Iterable elements, {bool growable: true})

// 创建包含所有元素的可改变长度列表
List growableList = new List.from([1,2,3]);
growableList.add(4);

List.filled(int length, E fill, {bool growable: false})

// 为所有元素统一赋值
List fixedLengthList = new List<int>.filled(3,0);

List.generate(int length, E generator(int index), {bool growable: true})

// 用生成器给所有元素赋初始值
List fixedLengthList = new List<int>.generate(4,(int index){
    return index * index;
});

Map

Map()

Map<String, int> map = {"a":1, "b":2, "c":3};  
print(map["a"]);

Map.fromIterable(Iterable iterable, {K key(element), V value(element)})

List<int> list = [1, 2, 3];
// 以下代码用到了速写语法,后面会详细讲解
Map<String, int> map = new Map.fromIterable(list,
        key: (item) => item.toString(),
        value: (item) => item * item);
// 1 + 4 = 5
print(map['1'] + map['2']);
// 9 - 4 = 5
print(map['3'] - map['2']);

Map.fromIterables(Iterable keys, Iterable values)

List<String> letters = ['b', 'c'];
List<String> words = ['bad', 'cat'];
Map<String, String> map = new Map.fromIterables(letters, words);
// bad + cat = badcat
print(map['b'] + map['c']);

Set

集的每个对象只能出现一次,不能重复

Set villains = new Set.from(["A", "B", "C"]);

Buidler模式,使用..来表示

Dart 默认支持Buidler模式,使用..来表示

".." is the cascaded method invocation operation. The ".." syntax invokes a method (or setter or getter) but discards the result, and returns the original receiver instead.

var address = getAddress();
address.setStreet(“Elm”, “13a”);
address.city = “Carthage”;
address.state = “Eurasia”
address.zip(66666, extended: 6666);

getAddress()
  ..setStreet(“Elm”, “13a”)
  ..city = “Carthage”
  ..state = “Eurasia”
  ..zip(66666, extended: 6666);

null-aware operators

?? if null operator. expr1 ?? expr2 evaluates to expr1 if not null, otherwise expr2.

??= null-aware assignment. v ??= expr causes v to be assigned expr only if v is null.

x?.p null-aware access. x?.p evaluates to x.p if x is not null, otherwise evaluates to null.

x?.m() null-aware method invocation. x?.m() invokes m only if x is not null.

  var x = null;
  x ??= 'are the null-aware operators, friendly to';
  print(x);
  // 打印出:are the null-aware operators, friendly to
  
  // null-aware method invocation
  var isNull = null;
  print(isNull?.foo()); // null (does not throw exception)
  // 打印出:null

类型运算符 as is

Pub仓库

推荐看https://flutter.io/using-packages/#css-example
在Pub上可以下载到支持各种功能的包,首页在根目录下建立pubspec.yaml文件,

name: test_app  
dependencies:
  sqljocky: ^0.14.1

name是包的名称,dependencies是需要依赖的包名,上面的sqljocky是用来连接MySQL的。
执行pub get命令下载相关依赖包,不过官方建议使用flutter packages get而不是pub get.

泛型

dart中所有基本类型数组和列表都是泛型,泛型可以减少代码重复,提高代码的可读性。

abstract class Cache<T> {
  T getByKey(String key);
  setByKey(String key, T value);
}

异常

dart会抛出并捕获异常。多个类型可以指定多个异常处理,可以使用on和catch或两者都用,使用on指定异常类型,使用catch给异常处理程序一个异常对象。

try {
      breedMoreLlamas();
    } on OutOfLlamasException {
      //指定的异常
      buyMoreLlamas();
    } on Exception catch (e) {
      //所有异常
      print('Unknown exception: $e');
    } catch (e) {
      //没有指定类型,处理所有异常
      print('Something really unknown: $e');
    }finally{
        //一定会执行
    }

声明实例变量时,所有未初始化的实例变量的值为null

类的构造函数

Dart类与构造函数
命名构造函数

void main(){
    var point = new Point.fromJson({'x':2, 'y':4});
}

class Point {
    int x;
    int y;

    Point(this.x, this.y);

    // 命名构造函数
    Point.fromJson(Map json) {
        x = json['x'];
        y = json['y'];
    }
}

父类的构造函数
子类构造函数调用父类的默认构造函数,如果父类没有默认构造函数,必须手动调用父类的构造函数,在 : 号后面指定父类的构造函数

void main(){
    var emp = new Employee.fromJson({});
}

class Person {
    Person.fromJson(Map data) {
        print("in Person");
    }
}

class Employee extends Person {
    Employee.fromJson(Map data) : super.fromJson(data) {
        print("in Employye");
    }
}

使用@override注释重写,使用@proxy注释来忽略警告

相关文章

  • Dart 基础(四)

    前言笔者在之前已经写了3篇Dart的基础文章了。Dart 基础 (一)Dart 基础 (二)Dart 基础 (三)...

  • Dart 基础 (三)

    前言笔者在之前已经写了2篇Dart的基础文章了。Dart 基础 (一)Dart 基础 (二) 本文是Dart基础的...

  • dart入门潜修系列教程

    dart入门潜修基础篇之基本语法和内置类型dart入门潜修基础篇之方法dart入门潜修基础篇之操作符dart入门潜...

  • 一.Dart语法-操作符、方法与异常

    Dart基础 运行Dart 代码可以使用 dart xxx.dart,dart命令需要配置环境变量,将 “${F...

  • Dart基础(一)

    级别: ★☆☆☆☆标签:「Flutter 」「Dart」「Dart基础类型」作者: WYW审校: QiShare...

  • Flutter学习笔记

    Dart基础语法 一、选择开发工具 首先需要安装Dart SDK(https://www.dart-china.o...

  • Dart语言基础,Dart 基础

    Dart 的main方法有两种声明方式 注释 变量的声明 、命名规则、数组类型 Dart是一个强大的脚本类语言,可...

  • Dart 基础

    Dart 基础汇总 点我直达[https://xxxixxxx.github.io/categories/Dart...

  • Flutter - 入门

    Dart基础 如果你有JS、Java、Kotlin、Swift等语言的基础,入门几乎没啥子难度 程序入口 dart...

  • Dart record

    参考 Dart学习笔记(29):异步编程Dart编程字典子不语归来 的 Dart2基础何小有Dart实例教程 数组...

网友评论

      本文标题:Dart基础

      本文链接:https://www.haomeiwen.com/subject/ebtxfftx.html