Skip to content

学习笔记-Dart基础语法 #7

Description

@ycshill

Dart 基础

  1. 列表项

标签(空格分隔): Flutter


常量和变量

变量

  • var
    如何不赋值的话,就是 null,和js中的差不多;
  • final
    声明只能赋值一次的变量;

常量

  • const
var a;
print(a);  // null

a = 10;
print(a); // 10

a = 'Hello Dart';
print(a);  // Hello Dart;

//  总结 var 和js 一样,  未初始化的时候是 null,(变量)

// 声明一个只赋值一次的变量
final b = 20;
print(b);  // 20;

// 声明一个常量(编译时)
const c = 30;
print(c); // 30

数据类型

内置数据类型

  • Number
  • String
  • Boolean
  • List(列表)
  • Map(键值对)

Number

  • int

  • double
    注意定义了double类型字段的时候,可以赋值为整数的,但是打印的时候还是浮点的

    num a = 10;
    print(a); // 10
    a = 10.5;
    print(a); // 10.5
    
    int b = 10;
    // b = 10.5;  不可以
    print(b);
    
    double c = 10.5;
    print(c);  // 10.5
    c = 2;
    print(c); // 2.0
    
  • 数值型操作

    • 运算符+,-,*,/,%,~/;
      • '+' : 有一个是double,就会自动转化为double;
      • '/': 返回的是double;
      • '~/': 返回的是取正;
      • '%': 返回的是取余的;
      print(a + b);  // 有一个是浮点型的就是浮点型的 20.5
      print(b + d);  // 21
      print(d - a); // 0.5
      print(b * d); // 110;
      print(d/a); // 1.0476190476190477
      print(d ~/a); // 1 取整
      print(d%a); // 0.5 取余
    
    • 常用属性

      • isNaN
      • isEven:是否是偶数
      • isOdd:是否是奇数
       int a = 2;
       print(a.isNaN); // false
       print(a.isEven); // true
       print(a.isOdd); // false
      
    • 常用方法

      • abs()
      • round() 四舍五入
      • floor() 向下取整
      • ceil() 向上取整
      • toInt()
      • toDouble()
      int a = -100;
      print(a.abs());
      
      double b = 10.5;
      print(b.round()); // 四舍五入 11
      print(b.floor()); // 向下取整 10
      print(b.ceil()); // 向上取整 11
      
      print(b.toInt()); // 10
      print(a.toDouble());
      

String

  • 创建字符串
    • 使用单引号或者双引号创建字符串;
    • 使用三个单引号或者双引号创建字符串;
    • 使用r创建raw(原生-不对特殊字符进行转换)的字符串;
    String a = 'hello string'; // "" 使用单引号,双引号创建字符串
    print(a);  // hello string
    
    String b = ''' hello
    multi line string'''; // """  使用三个单引号,双引号创建多行字符串
    print(b);
    // hello
    // multi line string
    
    String c = 'hello  \n not raw'; // \n 会被转换为换行符
    print(c);
    // hello
    // not raw
    
    String d = r'hello \n raw'; // 使用r创建原始的raw字符串, 其中的\n不会被转义
    print(d); // hello \n raw
    
  • 字符串的操作
    • '+' : 连接;
    • '*': *4 拼接四个一样的字符串;
    • '==': 判断是否相等;
    • '[]': [2]返回字符串第二个位置的元素;
    • 插值表达式:${表达式}
    • 插值变量:$a;
    • 常用属性:
      • length
      • isEmpty
      • isNotEmpty;
    • 常用方法:
      • contains(str) 是否包含某个字符串;
      • subString(start, end) 截取字符串,掐头去尾;
      • startWith(str) 是否是以**开头;
      • endsWith(str) 是否是以**结尾;
      • indexOf(str) 所含第一字符所在的开始位置;
      • lastIndexOf(str) 所含最后一个字符所在的位置;
      • toLowerCase() 转为小写;
      • toUpperCase() 转为大写;
      • trim() 去掉左右两边的空格;
      • trimLeft() 去掉左边的空格;
      • trimRight() 去掉右边的空格;
      • split() 以拆分为数组;
      • replaceAll(pattern, str) 替换所有匹配的;
      • replaceFirst(pattern, str) 替换第一个匹配的;
      • replaceRange(start, end, str) 替换指定范围的;
      // 常用的操作
      String a = 'i am a girl';
      print(a + 'i love life'); // i am a girli love life
      print(a*3); // i am a girli am a girli am a girl
      print(a[2]); // a
      
      int b = 10;
      int c = 10;
      print('b is $b'); // b is 10
      print('a + b = ${b + c}'); // a + b = 20
      
      // 常用的属性
      print(a.length); // 11
      print(a.isEmpty); // false
      print(a.isNotEmpty); // true
      
      // 常用的方法
      String d = 'this is a sun day';
      print(d.contains('is')); // true;
      print(d.substring(2,4)); // 掐头去尾 is
      print(d.startsWith('a')); // false
      print(d.endsWith('ay')); // true
      print(d.indexOf('is'));  // 2
      print(d.lastIndexOf('is')); // 5
      print(d.toLowerCase()); // this is a sun day
      print(d.toUpperCase()); // THIS IS A SUN DAY
      print(d.split(' ')); // [this, is, a, sun, day]
      print(d.replaceAll('s', 'w')); // thiw iw a wun day
      print(d.replaceFirst('s', 'w')); // thiw is a sun day
      print(d.replaceRange(0, 5, 'r')); // ris a sun day
      String e = '   this is a sun day   ';
      print(e.trim()); // this is a sun day
      print(e.trimLeft());
      print(e.trimRight()); //    this is a sun day
      

Boolean

  • true
  • false
 bool a = true;
 print(a); // true;

列表List(数组)

list和js中的数组很相似

  • 创建List

    • 直接声明
    • 创建不可变的List
    • 构造创建
    // 创建List
    List a = [1, 3, 4, true, 'hello'];
    print(a); // [1, 3, 4, true, hello]
    List b = const [1, 2, 4];
    //  b[1] = 'eh'; // Cannot modify an unmodifiable list
    List c = new List();
    print(c); // []
    
  • 常用操作

    • [] 获取i的值,或者修改i位置的值;
    • length 获取数组的长度;
    • add(dynamic value) 在末尾添加元素
    • addAll(Iterable iterable) 添加可遍历的元素;
    • insert(int index, dynamic ele) 把ele添加到指定的位置;
    • remove(ele) 删除指定元素
    • removeLast() 删除最后一个
    • removeAt(index) 删除指定位置的元素
    • removeRange(start, end) 删除几个元素,掐头去尾
    • clear() 删除;
    • indexOf(ele) 返回第一个匹配元素的位置,没有则返回-1
    • lastIndexOf(ele) 返回最后一个匹配字符的位置,没有则返回-1;
    • sort([int compare(E a, E b)]) 排序里面可以传入哪种方式进行比较;
    • sublist(start) 返回一个截取的数组;
    • shuffle()
    • asMap() 将List 转换为Map
    • forEach(void f(E element)) 循环遍历 传入一个函数
      // List常用的操作
      List d = [1, true, 'hello'];
      print(d); // [1, true, hello]
      print(d[0]); // 1
      d[0] = 4;
      print(d); // [4, true, hello]
      print(d.length); // 3
      d.add('world');
      print(d); // [4, true, hello, world]
      d.insert(2, false); // 将ele插入数组的指定位置
      print(d); // [4, true, false, hello, world]
      d.remove('hello');
      print(d); // [4, true, false, world]
      d.removeLast(); // 删除最后一个
      print(d); // [4, true, false]
      d.removeAt(1); // 删除指定位置
      print(d); // [4, false]
      d.addAll([5, 6, 0]);
      print(d); // [4, false, 5, 6, 0]
      d.removeRange(0, 1);
      print(d); // [false, 5, 6, 0] 掐头去尾
      print(d.indexOf(6)); // 2
      d.addAll([5, 6, 0]);
      print(d); // [false, 5, 6, 0, 5, 6, 0]
      print(d.lastIndexOf(0)); // 6
      d.remove(false);
      print(d); // [5, 6, 0, 5, 6, 0]
      d.sort();
      print(d); // [0, 0, 5, 5, 6, 6]
      print(d.sublist(2)); // [5, 5, 6, 6]
      d.shuffle();
      print(d); // [6, 5, 0, 6, 5, 0]
      d.forEach(print);  
      /**
       *
        flutter: 0
        flutter: 5
        flutter: 6
        flutter: 0
        flutter: 5
        flutter: 6
       */
       print(d.asMap()); // {0: 5, 1: 5, 2: 0, 3: 6, 4: 6, 5: 0}
    

Map

键值对的形式,有点像对象

  • 创建Map
    • 直接构建 var a = {'first': 'a', 'second': 'b'};
    • 创建不可变的Map var a = const {'first': 'a', 'second': 'b'};
    • 构造创建var a= new Map();
// 创建Map
Map a = {
'name': 'lily',
'age': '26',
};
print(a); // {name: lily, age: 26}
// 创建一个不可变的map
Map b = const {
'name': 'lily',
'age': '26',
};
// b['name'] = 'xiaoming'; // Cannot set value in unmodifiable Map
print(b);
Map c = new Map();
print(c); // {}
  • 常用的操作
    • [] 获取和改变;
    • length
    • isEmpty()
    • isNotEmpty();
    • keys() 获取key;
    • values();
    • containsKey(key);
    • containsValue(val);
    • remove(key) 删除指定key的元素;
    • forEach(void f(K key, V value));
    void main() {
      runApp(MaterialApp(
        title: 'dart 的基础语法',
        home: FirstPage(),
      ));
    
      // 创建Map
      Map a = {
        'name': 'lily',
        'age': '26',
      };
      print(a); // {name: lily, age: 26}
      // 创建一个不可变的map
      Map b = const {
        'name': 'lily',
        'age': '26',
      };
      // b['name'] = 'xiaoming'; // Cannot set value in unmodifiable Map
      print(b);
      Map c = new Map();
      print(c); // {}
    
      // 常用的操作
      Map d = {
        'name': 'lily',
        'age': '26',
      };
      print(d['name']); // lily
      d['name'] = 'xiao';
      print(d); // {name: xiao, age: 26}
      print(d.length); // 2
      print(d.isNotEmpty); // true
      print(d.isEmpty); // false
      print(d.keys); // (name, age)
      print(d.values);  // (xiao, 26)
      print(d.containsKey('name')); // true
      print(d.containsValue(3)); // false
      d.remove('name');
      print(d); // {age: 26}
      d.forEach(getKeyValue); //key-age, value-26
    }
    
    void getKeyValue(key, value) {
      print('key-$key, value-$value');
    }
    

dynamic

可变数据类型;

dynamic a = 0;
print(a); // 0
a = 'hello';
print(a); // hello

List arr = new List<dynamic>();
arr.add(1);
arr.add('hello');
print(arr); // [1, hello]

运算符

算数运算符

  • '+'
  • '-'
  • '*'
  • '/' : 除
  • '~/':取整
  • '%':取余
int a = 10;
int b = 11;

print(a + b); // 21
print(a - b); // -1
print(a * b); // 110
print(b / a); // 1.1
print(b ~/ a); // 1
print(b % a); // 1

关系运算符

  • '==' : 判断内容是否相等;
  • '!='
  • '>'
  • '<'
  • '>='
  • '<='
  • 前++(先++,在取值),后++(先取值做运算,再++);
  • 前--,后--
int a = 10;
int b = 11;

print(a == b); // false
print(a != b); // true
print(a > b); // false
print(a < b); // true
print(a >= b); // false
print(a <= b); // true
print(a++); // 10
print(++a); // 12 上面的表达式使用a的值的时候,就++啦
print(a--); // 12
print(--a); // 10

String strA = '123';
String strB = '123';
print(strA == strB); // true

逻辑运算符

  • '!' :取反
  • '&&'
  • '||'
bool a = true;
bool b = false;
print(!a); // false
print(a && b); // false
print(a || b); // true

赋值运算符

  • 基础运算符
    • '=';
    • '??=' : b ??= a如果b有值的话,就取b的值,如果b没值的话,就取=后面的值;
  • 复合运算符
    将进行操作后的值赋值给前面的值;
    • '+='
    • '-='
    • '*='
    • '/='
    • '%='
    • '~/='
int a = 10; // =
print(a); // 10

int b;
b ??= a;
print(b); // 10; 如果b没有值,就会读取 = 后面的值

int c = 5;
c ??= a;
print(c); // 5 如果c有值,就会读取c本身的值

print(a += b); // 20
print(a -= b); // 10
print(a *= b); // 100
// print(a /= b); //  value of type 'double' can't be assigned to a variable of type 'int'
print(a ~/= b); // 10
print(a %= b); // 0

double d = 11.0;
print(d /= b); // 1.1

条件表达式

  • 三目运算符 ? = :
  • ??运算符 如果前面的值为null,则取后面的值,否则就是前面的值
bool isMan = false;
print(isMan ? '$isMan, he is a man' : '$isMan, he is not a man'); // false, he is not a man
isMan = true;
print(isMan ? '$isMan, he is a man' : '$isMan, he is not a man'); // true, he is a man

String strA;
String strB = 'hello';
print(strA ?? strB); // hello, 如果前面是null的话,就读取后面的
print(strB ?? strA); // hello, 如果前面不是null的话,就读取前面的值

控制语句

if语句

  • if
  • if else
  • if... else if... else...

for语句

  • for
  • for in 语句
List arr = [1, 2, 3, 4];
for(int i = 0; i < arr.length; i++){
print('$i--${arr[i]}');
/***
  flutter: 0--1
  flutter: 1--2
  flutter: 2--3
  flutter: 3--4
 */
}

for(int item in arr){
print(item);
/**
  flutter: 1
  flutter: 2
  flutter: 3
  flutter: 4
 */
}

while 语句

  • while 语句
  • do...while 语句
int count = 0;
  while(count < 5) {
    print(count++);
  }
  /**
    flutter: 0
    flutter: 1
    flutter: 2
    flutter: 3
    flutter: 4
  */
  print('+++$count+++'); // 5

  do {
    print(count--);
  } while (count > 0 && count < 5);
  /**
   *
  flutter: 5
  flutter: 4
  flutter: 3
  flutter: 2
  flutter: 1
   */

break 和 continue 语句

  • break
    break 跳出本次最近的循环;

  • continue
    continue 进入跳过本次循环,进入下一次循环;

      List arr = [1, 2, 3, 4];
      for (int item in arr) {
        if (item == 2) {
          break; // 跳出按着的循环
        }
        print(item); // 1
      }
      print('----------');
      for (int item in arr) {
        if (item == 2) {
          continue;  // 跳出本次循环
        }
        print(item); // 1 3 4
      }
      print('-------');
      List inner = ['a', 'b', 'c'];
      for(int item in arr) {
        for(String i in inner) {
          print(i);
          break;  // 跳出临近的本次循环
          /**
           * flutter: a
            flutter: a
            flutter: a
            flutter: a
           */
        }
      }
    

switch-case 语句

和其他的语句不同的是可以加入continue flag,会跳转到flag的地方执行语句;

String language = 'java';
  // break;
  switch(language) {
    case 'js':
      print('js');
      break;
    case 'java':
      print('java');
      break;
    case 'dart':
      print('dart');
      break;
    default:
      print('none');
  }
  // 使用 continue
  String language1 = 'dart';
  switch(language1) {
  Tag:
   case 'js':
      print('js');
      break;
    case 'java':
      print('java');
      break;
    case 'dart':
      print('dart');
      continue Tag;
    default:
      print('none');
  }
  /**
   * flutter: java
     flutter: dart
     flutter: js
   */

方法

方法特性

  • 方法也是对象,并且有具体类型Function;
  • 返回值类型、参数类型都可以省略;
  • 可以使用箭头函数;
  • 方法都有返回值,如果没有指定,默认return null

可选参数

可选参数要放在后面;

  • 可选命名参数:{param1, param2,...};
  • 可选位置参数:[param1, param2,...];
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  print(getPerson('lily', grade: '一年级')); // name-lily,age-null,grade-一年级
  print(getPersonInfo('lily',10,)); // 使用位置可选参数:name-lily,age-10,grade-null
}

// 使用命名可选参数
String getPerson(String name, {int age, String grade}) {
  return 'name-$name,age-$age,grade-$grade';
}

// 使用位置可选参数
String getPersonInfo(String name, [int age, String grade]) {
  return '使用位置可选参数:name-$name,age-$age,grade-$grade';
}

默认参数

void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  print(getPerson('lily', grade: '一年级')); // name-lily,age-10,grade-一年级
}

// 使用命名可选参数
String getPerson(String name, {int age = 10, String grade = "大学生"}) {
  return 'name-$name,age-$age,grade-$grade';
}

方法对象

  • 作为参数,传递给变量
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Function fun = printHello;  // 作为一个参数,传递给变量
  fun(); // hello

}

void printHello() {
  print('hello');
}

  • 作为函数的参数,传递给变量
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Function fun = printHello;  // 作为一个参数,传递给变量
  fun(); // hello

  List hello = ['h', 'e', 'l', 'l', 'o'];
  print(ListTimes(hello, times));  // [hhh, eee, lll, lll, ooo]

}

void printHello() {
  print('hello');
}

// 返回三次该字符串
String times(str) {
  return str * 3;
}

// 根据List 返回一个新的List
List ListTimes(List list, String times(str)) {  // 作为一个函数的参数传入
  for(int i = 0; i< list.length; i++) {
    list[i] = times(list[i]);
  }

  return list;
}

匿名方法

  • 可以赋值给变量,通过变量进行调用;
Function fun = (str) {
print('hello---$str');
};

fun('1'); // hello---1
  • 可在其他的方法中直接调用,或者传递给其他方法;
  • 格式
(参数1,参数2){
    方法体
    return 返回值;
}
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  // 匿名方法
  Function fun = (str) {
    print('hello---$str');
  };

  fun('1'); // hello---1

  // 自身直接调用
  ((){
    print('自己直接调用');
  })();

  List hello = ['h', 'e', 'l', 'l', 'o'];
  // 匿名函数作为参数传递
  // print(listTimes(hello, (str){ return str * 3; }));  // [hhh, eee, lll, lll, ooo]
  print(listTimes1(hello)); // [hhh, eee, lll, lll, ooo]

}

// 将自身调用三次
List listTimes(List list, String times(str)) {
  for (int i = 0; i < list.length; i++) {
    list[i] = times(list[i]);
  }

  return list;
}

// 匿名函数在方法中使用
List listTimes1(List list){
  Function fun = (str) { return str * 3; };
   for (int i = 0; i < list.length; i++) {
    list[i] = fun(list[i]);
  }

  return list;
}

闭包

  • 闭包是一个方法(对象);
  • 闭包定义在其他方法的内部;
  • 闭包能够访问外部方法中的局部变量,并且持有状态;
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Function fun = printCount();
  fun(); // 0
  fun(); // 1
 }

printCount() {
  int count = 0;

  // 一般都使用匿方法返回闭包函数
  return (){
    print(count++);
  };
}

异常处理

通过 throw 抛出异常,通过 try-catch(如果不知道是哪种类型) 或者 try-on(用于精确匹配) 捕获异常。

void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  // 使用 try-on try-catch 进行捕获
  try{
    divide(10, 0);
  }on IntegerDivisionByZeroException {  // on 是知道是哪种异常的时候,精确匹配
    print('Division by zero.');
  } catch(e) {  // 对于不确定类型的异常,可以用catch处理
    print(e);
  } finally { // 都会执行
    print('无论什么样都执行!');
  }
}

// 异常处理
divide(int a, int b) {
  if (b == 0) {
    // 通过throw 抛出异常
    throw new IntegerDivisionByZeroException();  // 抛出的是自带的异常
    // throw new Exception('Divide by zero'); // 抛出字符串异常
  } else {
    return a / b;
  }
}

类

定义

  • 简单的类
//一个简单的类
class Point {
  num x;
  num y;
}
void main() {
  var point = Point();
  point.x = 4; // Use the setter method for x.
  assert(point.x == 4); // Use the getter method for x.
  assert(point.y == null); // Values default to null.
}
  • 有构造函数
class Cat {
    String name;
    int age;
    Cat(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
void main() {
  Cat Tom = new Cat("Tom", 2);
    print(Tom.name);
}
  • 使用语法糖实现构造函数
class Cat {
    String name;
    int age;
    Cat(this.name ,this.age) 
}
void main() {
  Cat Tom = new Cat("Tom", 2);
    print(Tom.name);
}
  • 命名构造函数
class Cat {
    String name;
    int age;
    Cat(this.name ,this.age) 
    Cat.newBorn(){
        name = "Cherry";
        age = 0;
    }
}
void main() {
  Cat Cherry = new Cat.newBorn();
    print(Cherry.name);
}

类的组成

类的实例是由 方法和实例变量 组成的;

  • 使用类的成员;
    通过 . 引用实例的变量或者方法,可以使用 ?.;

    var p = new Person('lily');
    print(p.name);
    p?.name = 'wanghogn';  // 如果p不是null,把值设置为wanghogn
    

继承

import 'package:flutter/material.dart';


class FirstPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dart 的基础语法练习'),
      ),
      body: Center(
        child: Text('1212'),
      ),
    );
  }
}


void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Person p = new Person.born();
  print(p.name); // lily 这样的好处感觉在定义的时候不用初始化,在内部已经写好了,不错
  Person p1 = new Person.middle();
  print(p1.age); // 16

  Man man1 = new Man.small('honhong');
  print(man1.age);

  Man man2 = new Man.born();
  print('${man2.name}, ${man2.age}'); // man 0
}

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  Person.born(){
    name = 'baby';
    age = 0;
  }

  Person.middle() {
    name = 'junior';
    age = 16;
  }

}

// 实现继承,实现继承,在里面不用定义变量,父类命名的构造函数不会被子类继承,要使用:调用
class Man extends Person {
  Man(String name, int age):super(name, age);

  // 调用自身的构造函数,自身又调用父类的构造函数
  Man.small(String name):this(name, 0);

  Man.old(String name):this(name, 45);

  Man.born():super.born(){
    name= 'man';
  }
}

初始实例变量

void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Point dot = new Point(2, 4);
  print(dot.sum); // 6
}

class Point {
  final num x;
  final num y;

  final num sum;

  // 可以在构造函数主体运行之前初始化实例变量,初始值设定项用逗号分开
  // 这个挺好的,能够通过其他的变量来初始化其他的变量
  Point(x, y)
    : x = x,
      y = y,
      sum = x + y;

}

类中的函数

定义函数

void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Person xiaoming = new Person.born();
  xiaoming.run(); //  i can run
}

class Person {
  String name;
  int age;

  Person(this.name, this.age);
  Person.born(){
    name = 'baby';
    age  = 0;
  }

  // 定义方法
  run() {
    print('i can run');
  }
}

函数的重写

void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

 Man xiaoming = new Man('xiaoming', 24);
 xiaoming.run(); // i am a man, i can run
}

class Person {
  String name;
  int age;

  Person(this.name, this.age);
  Person.born(){
    name = 'baby';
    age  = 0;
  }

  // 定义方法
  run() {
    print('i can run');
  }
}

class Man extends Person{
  Man(String name, int age):super(name, age);

  // 重写方法
  @override
  run() {
    print('i am a man, i can run');
  }
}

getter setter

dart中通过使用get和set关键字来实现getter和setter,get 在定义的时没有括号也没有参数;

void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  offsetPoint dot = offsetPoint(1, 2, 10);
  print(dot); // offsetPoint{x=11, y=12}
  print(dot.x); // 11 ,调用get
  print(dot.y); // 12
  dot.x = 4;  // 调用set
  print(dot); // offsetPoint{x=14, y=12}
}

class offsetPoint{
  int _x;
  int _y;
  int offset;

  offsetPoint(int x, int y, int offset)
    : _x = x,
      _y = y,
      offset = offset {
        print('初始化实例变量');
      }

  // 定义一个getter
  int get x => _x + offset;
  // getter 不能有参数,连括号都要删掉
  int get y {
    return _y + offset;
  }

  // 定义setter
  void set x(int x) => _x = x;
  void set y(int y) => _y = y;

  @override
  String toString() {
    return 'offsetPoint{x=$x, y=$y}';
  }
}

抽象方法和抽象类

  • 抽象类使用 abstract 关键字定义,抽象方法只能存在于抽象类中;
  • 除非定义了工厂构造函数,抽象类不能被实例化;
  • 抽象方法以(;)结尾,没有函数体
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Man p1 = new Man();
  p1.eat(); // i eat meat;
}

// 定义一个抽象类
abstract class Person {
  // 定义一个抽象方法
  void eat();
}

class Man extends Person {
  void eat() {
    print('i eat meat');
  }
}

隐式接口(暂时没有找到一个比较好的例子)

之所以叫隐式接口,是因为**没有关键字 interface **,一个类可以实现多个接口 class Point implements Comparable, Location {...};

静态方法

通过在方法前面添加 static 来实现;静态方法要通过类直接调用;

mixins 为类添加功能

  • 定义
    使用 mixin 关键字创建一个没有构造函数的扩展类;
  • 使用
    使用 with 关键字后跟多个类名来使用mixin
  • 和实现的区别,里面 不用实现方法,实例可以直接调用;
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  Man p1 = new Man('lily');
  p1.eat();  // i eat
}

mixin Person {
  String name;
  eat() {
    print('i eat');
  }
}

class Man with Person {
  String name;
  Man(this.name);
}

泛型

  • 类型变量,具有单字母名称,如 E、T、S、K 和 V;

为什么使用泛型

  • 指定泛型类型,可以生成更好的代码;
  // 使用泛型,可以更好的生成代码;
  var names = List<String>();
  names.add('kathy'); // 只能添加字符串
  • 减少代码重复;
    泛型允许在许多的类型之间共享同一个接口或和实现;例如有一个拥有用于存放int类型的数据,又有一个用于存放double类型的数据,就可以只定义一个接口,用泛型做一个定位符;
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  // 使用泛型,可以更好的生成代码;
  var names = List<String>();
  names.add('kathy'); // 只能添加字符串

  DataHolder<String> data1 = new DataHolder('string 类型的');
  print(data1.getData());

  DataHolder<int> data2 = new DataHolder(1);
  print(data2.getData());
}

// 这样写可以减少代码的重复
class DataHolder<T> {
  T data;

  DataHolder(this.data);

  getData() {
    return data;
  }

  setData(data) {
    this.data = data;
  }
}

使用字面量集合

  // 使用字面量集合
  List names = <String>['a', 'b', 'c'];
  Map person = <String, String>{
    'name': 'lily',
    'age': '10',
  };

构造函数的参数化类型,将类型放在后面的尖括号中;

var names = List<String>();

限制参数化类型

class Eeat<T extends Person> {
  String toString();
}

异步处理

Future

异步库里有个概念叫做 Future,就像是 Promise;

  • 引入库
import 'dart:async';
  • 使用 Future 创建一个异步
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  getAjoke().then((val) {
    print(val);  // his is a joke
  }).catchError((err) {
    print(err);  // 'no joke for you!1'
  });
}

// 使用Futter 实现异步
Future<String> getAjoke() {
  return new Future<String>(() {
    throw new Exception('no joke for you!1');
    return 'this is a joke';
  });
}
  • 使用 Future 模拟一个延时的方法
void main() {
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  getAjoke().then((val) {
    print(val);  // his is a joke
  }).catchError((err) {
    print(err);  // 'no joke for you!1'
  });
}

// 使用Future 创建一个比较费时的例子
Future<String> getAjoke() {
  return new Future<String>.delayed(new Duration(milliseconds: 2000), () {
    return 'this is a joke';
  });
}
  • async/await
    使用 async 方法和 await 表达式来配合实现异步,一个异步的函数可以包含多个 await 表达式;
void main() async{
  runApp(MaterialApp(
    title: 'dart 的基础语法',
    home: FirstPage(),
  ));

  try {
    String result = await getAjoke();
    print(result);
  } catch(e) {
    print(e);
  }
  print('现在可以执行');
}

// 使用Future 创建一个比较费时的例子
Future<String> getAjoke() {
  return new Future<String>.delayed(new Duration(milliseconds: 2000), () {
    return 'this is a joke';
  });
}

No activity

Activity on this issue will appear here.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions