Dart 语言基础分步指南

本文档详细介绍了Dart语言的基础知识,包括环境配置、变量与类型、流程控制语句、函数、类和对象、继承与多态、抽象类与接口、静态与权限,以及异步支持。通过实例代码演示了Dart的使用方法,适合初学者入门。
摘要由CSDN通过智能技术生成

官方文档参考

Dart 中文文档
Dart 在线编译器
Dart 语言概览
Dart Code
Dart 语法

Dart 语言学习开始的提前准备工作

  1. 先下载一个VSCode
  2. 安装VsCode插件、
    必须安装DartFlutter
    可选安装 ChineseGitLensBreaket Pair ColorizerCode Runner
  3. Flutter 0001、环境配置、参考我之前的文章

    VsCode插件

Dart 0000、Dart基本运行环境

  1. 创建一个文件夹 命名随意起我在这里命名了Test

  2. 使用VSCode 打开 Test文件夹
    使用VSCode 打开 Test文件夹

  3. 创建一个hello.dart文件、并且使用Code Runner插件进行快速执行
    创建main,dart文件
    在这里插入图片描述

  4. 执行出现 Dart_LoadScriptFromKernel: The binary program does not contain 'main'.

  5. 我们需要在debug里面进行创建 lalaunch.json文件
    在这里插入图片描述
    7、使用RunCode快捷 出现Dart_LoadScriptFromKernel: The binary program does not contain 'main'.
    尝试关闭vscode、重新打开hello.dart 进行ctrl + s 进行保存。
    再次使用 run code
    在这里插入图片描述

Dart 0001、变量与类型

  1. Dart是一个强类型语言
  2. 变量的定义
int age = 19;
String name = '宇夜';
  1. 系统的类型包含
  • 3.1 基本类型 : bool, num(int & double), String , enum
  • 3.2 范型 : List, Map
List<int> listA = [1, 2, 3];
List<String> listB = ['a', 'b', 'c'];

Map<int, String> m = {
  1: "str1",
  2: "str2",
};

enum Colors { Red, Blue, Green }
  1. dynamic 与 Object 的 区别
/**
 * dynamic 与 Object
 * 不同点 Object 只能使用Object属性与方法
 *       dynamic 编译器会提供所有的组合
 * 相同点 可以在后期改变赋值类型
*/

Dart 0001、变量与类型 源码

// 强类型语言

/**
 * 变量
 * 类型 变量名 = 值;
 * 如果一个变量阿兹定义之后没有赋值 -> null
 * 
*/

/**
 * 类型
 * 基本类型 : bool, num(int & double), String , enum
 * 范型 : List, Map
*/

int age = 19;
String name = '宇夜';

List<int> listA = [1, 2, 3];
List<String> listB = ['a', 'b', 'c'];

Map<int, String> m = {
  1: "str1",
  2: "str2",
};

enum Colors { Red, Blue, Green }
void main() {
  Colors c = Colors.Red;
  if (c == Colors.Red) {
    print(true);
    dynamicOrObject();
  }
}

/**
 * var 
 * 接受任何类型的变量
 * 一旦赋值,无法改变类型
*/

/**
 * dynamic 与 Object
 * 不同点 Object 只能使用Object属性与方法
 *       dynamic 编译器会提供所有的组合
 * 相同点 可以在后期改变赋值类型
*/

void dynamicOrObject() {
  var a = 1;
  // a = 'str1';  // var 无法改变类型

  dynamic d = 100;
  d = 'dynamic100';
  print(a);
  print(d);
  print(d.length); // length 是字符串的属性

  Object o = 200;
  o = 'ob200';
  print(o);
}


Dart 0002、流程控制语句

  1. 条件判断 if else
/**
* 条件判断
* if 与 其他语言差别不大
* Debug模式下 接受 bool类型,release接受任何类型
*/
bool isEven(int n) {
 if (n.isEven) {
   return true;
 } else {
   return false;
 }
}

  1. switch 语句 switch、case、return、default、break、continue
/**
* switch 语句
* 非空case在执行晚之后必须以break、return、continue的方式结束
* 空case继续执行
*/

enum Colors { Red, Blue, Green }

bool isRed(Colors color) {
 switch (color) {
   case Colors.Red:
     return true;
   case Colors.Blue:
   case Colors.Green:
   default:
     break;
 }
 return false;
}
  1. 循环语句 forwhiledo-while
void for_While() {}
List<int> listA = [1, 2, 3];

bool isPositive() {
 for (var n in listA) {
   if (n > 0) {
     return true;
   }
 }

 for (var i = 0; i < listA.length; i++) {
   if (listA[i] > 0) {
     return true;
   }
 }

 int n = 0;
 while (n < listA.length) {
   if (listA[n] > 0) {
     return true;
   }
   n++;
 }
 return false;
}

Dart 0002、流程控制语句 源码

void main() {
 // bool
 isRed2(Colors.Blue);
}

/**
* 条件判断
* if 与 其他语言差别不大
* Debug模式下 接受 bool类型,release接受任何类型
*/
bool isEven(int n) {
 if (n.isEven) {
   return true;
 } else {
   return false;
 }
}

/**
* switch 语句
* 非空case在执行晚之后必须以break、return、continue的方式结束
* 空case继续执行
*/

enum Colors { Red, Blue, Green }

bool isRed(Colors color) {
 switch (color) {
   case Colors.Red:
     return true;
   case Colors.Blue:
   case Colors.Green:
   default:
     break;
 }
 return false;
}

/**
* 循环语句
* for与其他语言差别不大
* while可以看作简化版的for
* do-while先执行一次、然后在判断
*/

void for_While() {}
List<int> listA = [1, 2, 3];

bool isPositive() {
 for (var n in listA) {
   if (n > 0) {
     return true;
   }
 }

 for (var i = 0; i < listA.length; i++) {
   if (listA[i] > 0) {
     return true;
   }
 }

 int n = 0;
 while (n < listA.length) {
   if (listA[n] > 0) {
     return true;
   }
   n++;
 }
 return false;
}

/**
* 跳转语句
* break结束整个循环
* continue结束当前循环
* 
*/
bool isRed2(Colors color) {
 switch (color) {
   case Colors.Red:
     return true;

   case Colors.Blue:
     print("Blue");
     // continue; //错误写法 switch语句中的continue语句必须有一个标签作为目标。尝试将与一个case子句关联的标签添加到continue语句中。
     continue Label_Green; // 这里label_Green表示执行下一个位置
   Label_Green:
   case Colors.Green:
     print("Green");
     return false;
   default:
     break;
 }
 return false;
}


Dart 0003、函数

  1. 函数写法
int calPower(int n) {
  return n * n;
}
  1. 函数如果是直接返回 那么可以直接简写
int calPower2(int n) => n * n;
  1. 函数变量作为参数
void func1() {
  var v_calPower = (n) {
    return n * n;
  };
  print(v_calPower(2)); // 打印2的平方
}
  1. 参数传递层层传递
void func2() {
  fun2_printPower(func2_calPower(8));
}

void fun2_printPower(var power) {
  print(power);
}

int func2_calPower(int n) => n * n;
  1. 函数的可选位置参数 可选参数可以不填写
/**
 * 可选位置参数
 * 可以用“[]”来标记可选的参数位置
*/
void func3() {
  int m1 = func3_calMulltipliction(4);
  print(m1); //16
  // 可选位置参数
  int m2 = func3_calMulltipliction(4, 5);
  print(m2);
  // 可命名参数
  int m3 = func3_calMulltipliction_2(8, b: 9);
  print(m3);
}

int func3_calMulltipliction(int a, [int? b]) {
  if (b != null) {
    return a * b;
  } else {
    return a * a;
  }
}
  1. 可命名参数 调用参数时候 能显示名称
/**
 * 可命名参数
 * 可以用“{}”来标记可选的命名参数
 * */
int func3_calMulltipliction_2(int a, {int? b}) {
  if (b != null) {
    return a * b;
  } else {
    return a * a;
  }
}
// 效果 其中b就是命名参数 int m3 = func3_calMulltipliction_2(8, b: 9);

Dart 0003、函数 源码

/**
 * 函数
 * 声明
 * 没有显示声明返回值类型默认当做dynamic
 * 
*/

void main() {
  int power = calPower(5);
  print(power);
  func1();
  func2();
  func3();
}

int calPower(int n) {
  return n * n;
}

/**
 * 上面的语法简写
 * =>表示
 *  */
int calPower2(int n) => n * n;

/**
 * 函数变量
 * 作为参数
*/
void func1() {
  var v_calPower = (n) {
    return n * n;
  };
  print(v_calPower(2));
}

/**
 * 参数传递
 * 层层传递
 * */

void func2() {
  fun2_printPower(func2_calPower(8));
}

void fun2_printPower(var power) {
  print(power);
}

int func2_calPower(int n) => n * n;

/**
 * 可选位置参数
 * 可以用“[]”来标记可选的参数位置
*/
void func3() {
  int m1 = func3_calMulltipliction(4);
  print(m1); //16
  // 可选位置参数
  int m2 = func3_calMulltipliction(4, 5);
  print(m2);
  // 可命名参数
  int m3 = func3_calMulltipliction_2(8, b: 9);
  print(m3);
}

int func3_calMulltipliction(int a, [int? b]) {
  if (b != null) {
    return a * b;
  } else {
    return a * a;
  }
}

/**
 * 可命名参数
 * 可以用“{}”来标记可选的命名参数
 * */
int func3_calMulltipliction_2(int a, {int? b}) {
  if (b != null) {
    return a * b;
  } else {
    return a * a;
  }
}


Dart 0004、类和对象

  1. 类的定义 使用关键字class
class Person {
}
  1. 类的构造函数 两种写法
class Person {
  int age = 0;
  String? name;
  // 构造函数
  // Person(int age, String name) {
  //   this.age = age;
  //   this.name = name;
  // }
  // 构造函数简写
  Person(this.age, this.name);
  }
  1. 命名构造函数
class Person {
  int age = 0;
  String? name;
  /**
   * 命名构造函数
   * 更加方便
  */
  Person.fromList(List<dynamic> list) {
    age = list[0];
    name = list[1];
  }
  }

4.重定向构造函数

class Person {
  int age = 0;
  String? name;
  // 构造函数
  // Person(int age, String name) {
  //   this.age = age;
  //   this.name = name;
  // }
  // 构造函数简写
  Person(this.age, this.name);
  /**
   * 重定向构造函数
   * 调用另一个构造函数
  */
  Person.defalut(int age, String name) : this(age, name);
}

Dart 0004、类和对象 源码

/**
 * 类和对象
 * 
 * 1.定义
 * calss
 * 
 * 2.构造函数
 * 与类同名 
 * 没有显示提供,等价于提供一个空的构造函数
 * 没有析构函数 => 垃圾回收
*/
class Person {
  int age = 0;
  String? name;
  // 构造函数
  // Person(int age, String name) {
  //   this.age = age;
  //   this.name = name;
  // }
  // 构造函数简写
  Person(this.age, this.name);

  int howOld() {
    return age;
  }

  /**
   * 命名构造函数
   * 更加方便
  */
  Person.fromList(List<dynamic> list) {
    age = list[0];
    name = list[1];
  }

  /**
   * 重定向构造函数
   * 调用另一个构造函数
  */
  Person.defalut(int age, String name) : this(age, name);
}

void main() {
  Person a = new Person(20, 'A');
  print(a.howOld());

  Person b = new Person.fromList([30, 'B']);
  print(b.howOld());
}



Dart 0005、继承与多态

  1. 继承 基于 类 先有类 才有继承
  2. 多态和继承没多大差别
// 类
class Person {
  int age = 0;
  String? name;
  Person(this.age, this.name);

  Person.fromList(List<dynamic> list) {
    age = list[0];
    name = list[1];
  }

  Person.defalut(int age, String name) : this(age, name);

  int howOld() {
    return age;
  }
}

/**
 * 继承
 * 继承一个基类: extends
 * 调用基类方法: super
*/
class Male extends Person {
  Male(int age, String name) : super(age, name);
  @override
  int howOld() {
    return age + 1;
  }
}

void main() {
  Person a = new Person(20, 'A');
  print(a.howOld());

  Person b = new Male(30, 'B');
  print(b.howOld());
}

Dart 0005、继承与多态 源码

// 类
class Person {
  int age = 0;
  String? name;
  Person(this.age, this.name);

  Person.fromList(List<dynamic> list) {
    age = list[0];
    name = list[1];
  }

  Person.defalut(int age, String name) : this(age, name);

  int howOld() {
    return age;
  }
}

/**
 * 继承
 * 继承一个基类: extends
 * 调用基类方法: super
*/
class Male extends Person {
  Male(int age, String name) : super(age, name);
  @override
  int howOld() {
    return age + 1;
  }
}

/**
 * 多态
 * 没有很大差别
*/

void main() {
  Person a = new Person(20, 'A');
  print(a.howOld());

  Person b = new Male(30, 'B');
  print(b.howOld());
}


Dart 0006、抽象类与接口

  1. 抽象类 关键字 abstract
/**
 * 抽象类与接口
 * 抽象类
 * 关键字 : abstract
 * 不能实例化
 * 抽象函数:声明但不实现
 * 派生类必须重写抽象类所有的抽象函数
*/
//  抽象类
abstract class Person {
  String getName();
  int getAage() {
    return 20;
  }
}
  1. 派生类 必须重写抽象类所有的抽象函数
// 派生类
// 必须重写抽象类所有的抽象函数
class Male extends Person {
  String getName() {
    return 'Male';
  }
}
  1. 接口 关键字 implements必须实现 除 构造函数外所有的成员函数
/**
 * 接口
 * 关键字: implements
 * Dart每个类都是接口
 * 必须实现除 构造函数外所有的成员函数
*/
class AA implements Male {
  @override
  int getAage() {
    return 20;
  }

  String getName() {
    return 'AA';
  }
}

Dart 0006、抽象类与接口 源码

/**
 * 抽象类与接口
 * 抽象类
 * 关键字 : abstract
 * 不能实例化
 * 抽象函数:声明但不实现
 * 派生类必须重写抽象类所有的抽象函数
*/
//  抽象类
abstract class Person {
  String getName();
  int getAage() {
    return 20;
  }
}

// 派生类
// 必须重写抽象类所有的抽象函数
class Male extends Person {
  String getName() {
    return 'Male';
  }
}

/**
 * 接口
 * 关键字: implements
 * Dart每个类都是接口
 * 必须实现除 构造函数外所有的成员函数
*/
class AA implements Male {
  @override
  int getAage() {
    return 20;
  }

  String getName() {
    return 'AA';
  }
}

void main() {
  // Person a = new Person();

  Person b = new Male();
  print(b.getName());
}


Dart 0007、静态与权限

  1. 静态与非静态的成员、成员函数区别
·静态非静态
修饰static
属于对象
访问成员、静态成员、成员函数、静态成员函数只能访问静态成员和静态成员函数
  1. 权限 无关键字使用符号"_" 表示权限不存在针对类的访问权限,只有针对包(package)的

Dart 0008、异步支持

  1. 异步支持 IO处理
  2. 异步运算 Future + async + await
  3. 异步运算(async) -> 延长队列(await) -> 等待结果(Future)

async 和 await操作

/**
 * 简介-异步支持
 * async 与 await
 * await 关键字 必须在 async 函数内部使用
*/

getData(String data) async {
  print(data);
  data = await Future.delayed(Duration(seconds: 2), () {
    return "网络数据";
  });
  print(data); // 网络数据
}

Future

/**
 * Future
 * 表示异步操作的最终完成(或失败)
 * 只会有一个结果
 * 返回值 仍然是Future类型
 * */

Future.then

Future<String> Future_then_getData() async {
  // 成功操作
  // return await Future.delayed(Duration(seconds: 2), () {
  //   return "Future_网络数据";
  // });
  // 抛出异常操作
  return await Future.delayed(Duration(seconds: 2), () {
    // throw 抛出一个异常
    throw AssertionError("Future_then_getData");
  });
}

Future.then内部的onerror

  Future<String> futureThen = Future_then_getData();
  futureThen.then((value) {
    print(value);
  }, onError: (e) {
    print(e);
  });

Future.catchError

  // Future.catchError
  Future<String> futureCatchError = Future_catchError_getData();
  futureCatchError.then((value) {
    print(value);
  }).catchError((e) {
    print(e);
  });

Future.wait

/**
     * Future.wait
     * 等待多个异步任务执行结束后再执行
     * 接受一个future数组参数
    */

  Future.wait([
    Future.delayed(new Duration(seconds: 2), () {
      return "hello";
    }),
    Future.delayed(new Duration(seconds: 4), () {
      return " world";
    })
  ]).then((results) {
    print(results[0] + results[1]);
  }).catchError((error) {
    print(error);
  });

Future.whenComplete

 /**
    * Future.whenComplete
    * 表示无论失败或者成功,都会调用
    */

Dart 0008、异步支持 源码

/**
 * 异步支持 iO处理
 * 异步运算 Future + async + await
 * 异步运算(async) -> 延长队列(await) -> 等待结果(Future)
*/

/**
 * 简介-异步支持
 * async 与 await
 * await 关键字 必须在 async 函数内部使用
*/

void main() {
  //
  // String data = '初始化data';
  // getData(data);

  // Future.then 、then内部的onerror
  Future<String> futureThen = Future_then_getData();
  futureThen.then((value) {
    print(value);
  }, onError: (e) {
    print(e);
  });

  // Future.catchError
  Future<String> futureCatchError = Future_catchError_getData();
  futureCatchError.then((value) {
    print(value);
  }).catchError((e) {
    print(e);
  });

  /**
    * Future.whenComplete
    * 表示无论失败或者成功,都会调用
    */

  /**
     * Future.wait
     * 等待多个异步任务执行结束后再执行
     * 接受一个future数组参数
    */

  Future.wait([
    Future.delayed(new Duration(seconds: 2), () {
      return "hello";
    }),
    Future.delayed(new Duration(seconds: 4), () {
      return " world";
    })
  ]).then((results) {
    print(results[0] + results[1]);
  }).catchError((error) {
    print(error);
  });
}

getData(String data) async {
  print(data);
  data = await Future.delayed(Duration(seconds: 2), () {
    return "网络数据";
  });
  print(data); // 网络数据
}

/**
 * Future
 * 表示异步操作的最终完成(或失败)
 * 只会有一个结果
 * 返回值 仍然是Future类型
 * */

/**
  * Future.then
 */
Future<String> Future_then_getData() async {
  // 成功操作
  // return await Future.delayed(Duration(seconds: 2), () {
  //   return "Future_网络数据";
  // });
  // 抛出异常操作
  return await Future.delayed(Duration(seconds: 2), () {
    // throw 抛出一个异常
    throw AssertionError("Future_then_getData");
  });
}
/**
  * Future.then 可选参数
 */

/**
  * Future.catchError
 */
Future<String> Future_catchError_getData() async {
  return await Future.delayed(Duration(seconds: 2), () {
    // throw 抛出一个异常
    throw AssertionError("Future_onError");
  });
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宇夜iOS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值