参考:https://book.flutterchina.club/chapter1/dart.html#_1-4-1-%E5%8F%98%E9%87%8F%E5%A3%B0%E6%98%8E 参考:https://www.dartcn.com/guides/language/language-tour
// 变量申明 vs JavaScript
// JavaScript const let var new
// dart // 参考:https://www.dartcn.com/guides/language/language-tour // var 可以接受任何类型的变量 一旦赋值 便确定了类型 // void main(List args) { // var t=‘hello world’; // print(t); // }
// Object 是Dart所有对象的根基类,也就是说所有类型都是Object的子类(包括Function和Null),所以任何类型的数据都可以赋值给Object声明的对象mic与var一样都是关键词,声明的变量可以赋值任意对象。 而dynamic与Object相同之处在于,他们声明的变量可以在后期改变赋值类型。 // void main(List args) { // Object x; // dynamic y; // x=‘hello world’; // y=‘hello world’;
// x=100; // y=100; // print(x); // print(y); // }
// dynamic与Object不同的是,dynamic声明的对象编译器会提供所有可能的组合, 而Object声明的对象只能使用Object的属性与方法, 否则编译器会报错。如:
// dynamic a; // Object b; // void main() { // a = “”; // b = “”; // printLengths(); // }
// printLengths() { // // no warning // print(a.length); // // warning: // // The getter ‘length’ is not defined for the class ‘Object’ // print(b.length); // }
// final和const
// 一个 final 变量只能被设置一次,两者区别在于:const 变量是一个编译时常量,final变量在第一次使用时被初始化。 // void main(){ // //可以省略String这个类型声明 // // ignore: unused_local_variable // final str = “hi world”; // //final String str = “hi world”; // // ignore: unused_local_variable // const str1 = “hi world”; // //const String str1 = “hi world”; // print(str); // } //---------------------------------------------------------------------------------------------------------------------------------------------------------- // 数据 先声明类型 -->转化时在声明一下 dart 与typeScript 一样可以进行类型推断
// 数据类型 // Number 亚类型 num int 整型 double 带小数类型 相同类型运算得相同 不同类型得double // int // 整数值不大于64位, 具体取决于平台。 在 Dart VM 上, 值的范围从 -263 到 263 - 1. Dart 被编译为 JavaScript 时,使用 JavaScript numbers, 值的范围从 -253 到 253 - 1 // double // 64位(双精度)浮点数,依据 IEEE 754 标准。
// assert(false); 类似debug 处理断言
// var a=1; // 声明 int // var b=2.0; // 类型逆向 推导 double // var c=‘xxx’; // // 全局变量 声明 // String oneAsString = 1.toString(); // void main(List args) { // print(a); // print(b); // print(a/b);
// // num转字符串 // a=int.parse(‘1’); // print(a); // // 字符串转 数字 // c=1.toString(); // print?; // // 隐式转换 // print(1*2.0); // }
// String // 字符串 string
// var s = ‘string interpolation’; // void main(){ // // 表示不是全局变量 // // ignore: unused_local_variable // String str=‘我是文本’; // // ignore: unused_local_variable // var str1=‘Dart has ${s}, which is very handy.’; // print(str1); // } // 注意:== 运算符用来测试两个对象是否相等。 在字符串中,如果两个字符串包含了相同的编码序列,那么这两个字符串相等。
// Boolean // Dart 使用 bool 类型表示布尔值。 Dart 只有字面量 true and false 是布尔类型, 这两个对象都是编译时常量。 // void main(List args) { // // 检查空字符串。 // var fullName = ‘’; // assert(fullName.isEmpty);
// // 检查 0 值。 // var hitPoints = 0; // assert(hitPoints <= 0);
// // 检查 null 值。 // var unicorn; // assert(unicorn == null);
// // 检查 NaN 。 // var iMeantToDoThis = 0 / 0; // assert(iMeantToDoThis.isNaN);
// Runes 表示特殊编码 // Runes input = new Runes( // ‘\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}’); // 编码 转化成字符串 // print(new String.fromCharCodes(input)); // } // } // codeUnitAt codeUnit 转化成16位编码
// 数组(有序集合) // var list = [1, 2, 3]; //注意: Dart 推断 list 的类型为 List 。 如果尝试将非整数对象添加到此 List 中, 则分析器或运行时会引发错误 // void main(){ // // ignore: unused_local_variable // dynamic arr=[1,‘2’,3]; // arr.forEach((item)=>{ // print(item) // }); // }
// set 无序集合 // void main(List args) { // // ignore: unused_local_variable // var names = {}; // // Set names = {}; // 这样也是可以的。 // // var names = {}; // 这样会创建一个 Map ,而不是 Set 。 // // ignore: unused_local_variable // var halogens = {‘fluorine’, ‘chlorine’, ‘bromine’, ‘iodine’, ‘astatine’}; // names.add(‘fluorine’); // names.addAll(halogens); // print(names); // }
// Map 就是 对象
// 在变量 声明 // var obj={ // ‘key’:‘value’ // }; // void main(List args) { // print(obj[‘key’]); // }
// 函数声明
// var obj=Map(); // void main(List args) { // obj[‘a’]=‘b’; // print(obj); // }
// 函数 // var _nobleGases =[0,1,2];
// bool isNoble(int atomicNumber) { // return _nobleGases[atomicNumber] != null; // }
// void main(List args) { // // ignore: unused_local_variable // // var ss=_nobleGases[2]; // print(isNoble(2)); // }
// 可传 可不传 // void fn(int a, String b,[String device]){ // print(b+‘今年’+a.toString()); // }
// void main(List args) {
// fn( 18,‘小王’); // }
// 可传 可不传 // main(List args) { // fn(18,‘xiaoli’); // }
// void fn(int a,String b,[String device=‘xiaoming’]) { // print(b+‘今年18’+a.toString()+device+‘不知道’); // }
// 默认值 // void main(List args) { // fn(a: 18,b: ‘小李’); // }
// void fn({int a=1, String b=‘老王’}){ // print(b+‘今年’+a.toString()); // }
// 复杂数据类型
// main(List args) { // doStuff(); // }
// void doStuff( // {List list = const [1, 2, 3], // Map<String, String> gifts = const { // ‘first’: ‘paper’, // ‘second’: ‘cotton’, // ‘third’: ‘leather’ // }}) { // print(‘list: $list’); // print(‘gifts: $gifts’); // }
// void main(List args) { // fn([1,2,3,4,5]); // }
// void fn(List arr){ // arr.forEach((item) { // print(’${arr.indexOf(item)}:’+item.toString()); // }); // }
// 运算符
// void main(List args) { // // ignore: unused_local_variable // var isbool=false; // var Obj={}; // // 查看是什么数据类型 Protype类似 // if(Obj is Object){ // isbool=true; // } // // ignore: unnecessary_cast
// print(isbool); // }
// 赋值运算符
// main(List args) { // // ignore: unused_local_variable // var a=‘2’; // // ignore: unused_local_variable // var b; // b=a; // b??=‘3’; // print(b); // } // 逻辑运算符
// ! || &&
// 条件运算符 也可以 三目运算 a?b:c name ?? ‘Guest’
// main(List args) { // // ignore: unused_local_variabl // var name=null; // print( name ?? ‘Guest’); // }
// 级联运算符 …
// querySelector(’#confirm’) // 获取对象。 // …text = ‘Confirm’ // 调用成员变量。 // …classes.add(‘important’) // …onClick.listen((e) => window.alert(‘Confirmed!’));
// 控制流程语句
// void main(List args) { // if(true){ // // ignore: unused_local_variable // // var message = StringBuffer(‘Dart is fun’); // // for (var i = 0; i < 5; i++) { // // // message.write(’!’); // // print(’!’); // // }
// // var callbacks = []; // // for (var i = 0; i < 2; i++) { // // callbacks.add(() => print(i)); // // print(i); // // } // // callbacks.forEach(? => c());
// var collection = [0, 1, 2]; // for (var x in collection) { // print(x); // 0 1 2 // } // // while 循环在执行前判断执行条件: // // do-while 循环在执行后判断执行条件: // // break 和 continue // }
// var val=‘1’; // switch(val){ // case ‘1’: // case ‘2’: // fn(val); // break; // }
// var command = ‘CLOSED’; // switch (command) { // case ‘CLOSED’: // executeClosed(); // continue nowClosed; // // Continues executing at the nowClosed label.
// nowClosed: // case ‘NOW_CLOSED’: // // Runs for both CLOSED and NOW_CLOSED. // executeNowClosed(); // break; // } // }
// void executeClosed() { // }
// void executeNowClosed() { // }
// void fn(val){ // print(val); // }
// 调试 // void main(List args) { // // 确认变量值不为空。 // // ignore: unnecessary_null_comparison // // assert(command == null); 断言 debug 处理 // // 确认 URL 是否是 https 类型。 // // assert(urlString.startsWith(‘https’));
// // throw FormatException(‘Expected at least 1 section’);
// // throw ‘Out of llamas!’;
// try { // breedMoreLlamas(); // // ignore: nullable_type_in_catch_clause // } on Exception catch (e) { // // 其他任何异常 // print(‘Unknown exception: $e’); // } catch (e) { // // 没有指定的类型,处理所有异常 // print(‘Something really unknown: $e’); // }
// try { // breedMoreLlamas(); // } catch (e) { // print(‘Error: $e’); // Handle the exception first. // } finally { // cleanLlamaStalls(); // Then clean up. // } // }
// void breedMoreLlamas() { // throw FormatException(‘Expected at least 1 section’); // // throw ‘Out of llamas!’; // }
// void cleanLlamaStalls() { // print(‘我是谁!’); // }
// 类
// import ‘dart:math’;
// main(List args) { // distance(3,4); // }
// void distance(int x, int y){ // var p = Point(0, 0); // var c; // c?.y = 5; // // ignore: unused_local_variable // num distance = p.distanceTo(Point(x, y)); // print(distance); // print?;
// // 构造函数 // // ignore: unused_local_variable // var p1 = new Point(2, 2); // print(p1); // // 获取 数据类型 // print(‘The type of a is ${p1.runtimeType}’); // }
// 实例变量
// class Point { // late num x; // late num y; // Point(x,y){ // this.x=x; // this.y=y; // } // }
// void main() { // var point =new Point(4,5); // point.x = 4; // Use the setter method for x. // point.y=5;
// print(point.runtimeType); // print(point.x); // }
// class Person { // late String firstName;
// Person.fromJson(Map data) { // print(‘in Person’); // } // }
// class Employee extends Person { // // Person does not have a default constructor; // // you must call super.fromJson(data). // Employee.fromJson(Map data) : super.fromJson(data) { // print(‘in Employee’); // } // }
// main() { // var emp = new Employee.fromJson({});
// // Prints: // // in Person // // in Employee // if (emp is Person) { // // Type check // emp.firstName = ‘Bob’; // } // print(emp.firstName); // // ignore: unnecessary_cast // (emp as Person).firstName = ‘Bob1’; // print(emp.firstName); // }
// // 重定向构造函数 // void main(List args) { // // ignore: unused_local_variable // var p=new Point(1, 2); // var a=Point.alongXAxis(2);
// print§; // print(p.x); // print(p.y); // print(a); // print(a.x); // print(a.y);
// }
// class Point { // num x, y;
// // 类的主构造函数。 // Point(this.x, this.y);
// // 指向主构造函数 // Point.alongXAxis(num x) : this(x, 0);
// }
// // 常量构造函数 // void main(List args) { // var xx=new ImmutablePoint(3,3); // print(xx); // print(xx.x); // print(xx.y); // }
// class ImmutablePoint {
// final num x, y;
// const ImmutablePoint(this.x, this.y); // }
// 实例方法 // import ‘dart:math’;
// class Point { // num x, y;
// Point(this.x, this.y);
// num distanceTo(Point other) { // var dx = x - other.x; // var dy = y - other.y; // print(this.x); // print(x); // return sqrt(dx * dx + dy * dy); // } // }
// void main(List args) { // var p=new Point(0,0); // var p1=new Point(3,4); // print(p.distanceTo(p1));
// }
// 对象的 set get
// class Rectangle { // num left, top, width, height;
// Rectangle(this.left, this.top, this.width, this.height);
// // 定义两个计算属性: right 和 bottom。 // num get right => left + width; // set right(num value) => left = value - width; // num get bottom => top + height; // set bottom(num value) => top = value - 8; // }
// void main() { // var rect = Rectangle(3, 4, 20, 15);
// rect.bottom=35; // print(rect.top.toString()+‘top’); // print(rect.left.toString()+‘left’); // print(rect.width.toString()+‘width’); // print(rect.height.toString()+‘height’); // print(rect.right.toString()+‘right’); // print(rect.bottom.toString()+‘bottom’);
// rect.right = 12; // assert(rect.left == -8); // }
// 抽象方法 // abstract class Doer { // // 定义实例变量和方法 … // void doSomething(); // 定义一个抽象方法。 // }
// class EffectiveDoer extends Doer { // void doSomething() { // // 提供方法实现,所以这里的方法就不是抽象方法了… // print(‘你好’); // } // }
// void main(List args) { // // ignore: unused_local_variable // var e=new EffectiveDoer(); // e.doSomething();
// }
// 抽象类 // 这个类被定义为抽象类, // 所以不能被实例化。 abstract class AbstractContainer { // 定义构造行数,字段,方法…
void updateChildren(); // 抽象方法。 }
class EffectiveDoer extends AbstractContainer{ @override void updateChildren() { // ignore: todo // TODO: implement updateChildren print(‘虚拟类’); }
}
// void main(List args) { // var e=new EffectiveDoer(); // e.updateChildren(); // }
// 隐式接口 // 每个类都隐式的定义了一个接口,接口包含了该类所有的实例成员及其实现的接口。 如果要创建一个 A 类,A 要支持 B 类的 API ,但是不需要继承 B 的实现, 那么可以通过 A 实现 B 的接口。
// 一个类可以通过 implements 关键字来实现一个或者多个接口, 并实现每个接口要求的 API。 例如: // person 类。 隐式接口里面包含了 greet() 方法声明。 // class Person { // // 包含在接口里,但只在当前库中可见。 // final _name;
// // 不包含在接口里,因为这是一个构造函数。 // Person(this._name);
// // 包含在接口里。 // String greet(String who) => ‘Hello, $who. I am $_name.’; // }
// // person 接口的实现。 // class Impostor implements Person { // get _name => ‘’;
// String greet(String who) => ‘Hi $who. Do you know who I am?’; // }
// String greetBob(Person person) => person.greet(‘Bob’);
// void main() { // print(greetBob(Person(‘Kathy’))); // print(greetBob(Impostor())); // }
// 类的继承
// class Television { // void turnOn() { // _illuminateDisplay(); // _activateIrSensor(); // } // // ··· // void _illuminateDisplay() { // print(’_illuminateDisplay’); // } // void _activateIrSensor() { // print(’_activateIrSensor’); // } // }
// class SmartTelevision extends Television { // void turnOn() { // // super.turnOn(); // 相同函数名 调用父类 实例函数 // _bootNetworkInterface(); // _initializeMemory(); // _upgradeApps(); // }
// void _bootNetworkInterface() { // print(’_bootNetworkInterface’); // }
// void _initializeMemory() { // print(’_initializeMemory’); // }
// void _upgradeApps() { // print(’_upgradeApps’); // } // // ··· // }
// void main(List args) { // var p=new SmartTelevision(); // p._activateIrSensor(); // p.turnOn() // }
// 重写父类的内容
// class Television{ // void turnOn(){ // print(‘父类 turnOn’); // } // }
// class SmartTelevision extends Television { // @override // void turnOn() { // print(‘子类的 turnOn’); // } // // ··· // }
// void main(List args) { // var p=new SmartTelevision(); // p.turnOn(); // }
// 枚举属性
// enum Color { red, green, blue } // void main(List args) {
// print(Color.red.index); // print(Color.green.index); // print(Color.blue.index); // List colors = Color.values; // print(colors); // var aColor = Color.blue; // switch (aColor) { // case Color.red: // print(‘Red as roses!’); // break; // case Color.green: // print(‘Green as grass!’); // break; // default: // 没有这个,会看到一个警告。 // print(aColor); // ‘Color.blue’ // } // }
// 为类添加功能: Mixin // Mixin 是复用类代码的一种途径, 复用的类可以在不同层级,之间可以不存在继承关系。
// 通过 with 后面跟一个或多个混入的名称,来 使用 Mixin , 下面的示例演示了两个使用 Mixin 的类:
// class Performer{ // num one1=1; // void one(){ // print(‘one’); // } // }
// class Musical{ // num two2=2; // void two(){ // print(‘two’); // } // }
// class Musician extends Performer with Musical { // num three3=3; // void three(){ // print(‘three’); // } // // ··· // }
// void main(List args) { // var p=new Musician(); // p.one(); // p.two(); // p.three(); // print(p.one1); // print(p.two2); // print(p.three3); // }
参考:https://book.flutterchina.club/chapter1/dart.html#_1-4-1-%E5%8F%98%E9%87%8F%E5%A3%B0%E6%98%8E
// 函数回调处理
// List _nobleGases=[1,2,3,4];
// //不指定返回类型,此时默认为dynamic,不是bool // isNoble (int atomicNumber) { // print(_nobleGases[atomicNumber]); // return _nobleGases[atomicNumber] != null; // }
// void test(cb){ // print(cb(1)); // } // //报错,isNoble不是bool类型 // void main(List args) { // // print(isNoble(1)); // test(isNoble); // }
// 函数作为参数 // ignore: top_level_function_literal_block // var say = (str){ // print(str); // }; // void main(List args) {
// say(“hi world”); // }
// 函数作为参数进行传递
// void execute(var callback) { // callback(); // } // void main(List args) { // execute(() => print(“xxx”)); // }
|