从 JS 到 Dart:语法基础

声明:var final const。支持自动推断类型,但类型一直固定。未初始化的值为 null

Final vs const: const 编译时确定,final 运行时确定

基本类型:num int double String bool List Set Map

  1. int.parse('1'); // 1 1.toString()
  2. 带变量的字符串:${expression}
  3. 字符串连接:"字符串1" "字符串2"
    "字符串3";
    用加号也行
  4. 多行字符串
    '''
    这是第一行字符串。
    这是第二行字符串。
    '''
  5. enum Color { red, green, blue } Color.blue Color.blue.index
    级联调用:a...b=1;...c.d() 等价于 a.b=1; a.c.d()
    算数运算符:/除 ~/除法取整
    类型运算符:as is is!
    条件运算符:x ?? y 等价于 x ? x : y
    List 类型:list.add('x') list.insert(2, 'x') list.remove('x') list.sort() list.sort((a, b) => a < b ? 1 : -1) list.indexOf('x') list.contains('x')
    new 是可选的 List a = new List(); ✅ List a = List();✅
    Set 类型:set.add('x') set.addAll(['x', 'y', 'z']) set.remove('x') set.clear() set.contains('x') for(var x in set)
    Map 类型:map["k1"]="v1" map.remove("k1") map.clear() map.length map.foreach((k, v) {})
    忽略参数定义顺序的函数传参:定义:void enableFlags({bool bold, bool hidden}) {} enableFlags(hidden: true, bold: false);
    可选参数:void fun(int a, [int b=1, int c=2]){}
    闭包函数:(a, b) {return a>b} 闭包函数可以做闭包。箭头函数:(a, b)=>a>b
    类:_x私有属性 this.y✅ y✅(在没有歧义的情况下) 参数初始化 Point(int x, int y) : this.x = x, this.y = y {} Point(this.x, this.y);
    命名构造方法(预制构造方法)Point.origin() {x = 0;y = 0;} new Point.origin()
    工厂模式构造方法:factory X(String type){if(type=='type1') return x;if(type=='type1') return y;}一般要搭配命名构造方法使用
    extends implements
    运算符重载 bool operator <(Point v) => x < v.x && y < v.y;
    mixin 实现多继承:被混入的类 mixin X {...} 继承 class A extends Y with X, Z {...}
    异常可以直接 throw "string" 或 throw Exception("xxx")
    捕获异常:try {...} on AException {...} on BException {...} on Exception catch (e) {...} catch (e) {...}
    重新抛出异常:rethrow
    Finally
    异步处理 Future=Promise async/await
    异步数据序列 Stream await for (数据类型 变量 in stream类型变量) {// 处理数据}
相关推荐
@大迁世界1 分钟前
构建 Next.js 应用时的安全保障与风险防范措施
开发语言·前端·javascript·安全·ecmascript
is今夕1 小时前
postcss.config.js 动态配置基准值
javascript·vue.js·postcss
青茶绿梅*21 小时前
500字理透react的hook闭包问题
javascript·react.js·ecmascript
前端御书房2 小时前
Pinia 3.0 正式发布:全面拥抱 Vue 3 生态,升级指南与实战教程
前端·javascript·vue.js
NoneCoder2 小时前
JavaScript系列(84)--前端工程化概述
前端·javascript·状态模式
拉不动的猪4 小时前
刷刷题17(webpack)
前端·javascript·面试
Ama_tor4 小时前
网页制作06-html,css,javascript初认识のhtml如何建立超链接
javascript·css·html
烂蜻蜓4 小时前
Uniapp 中布局魔法:display 属性
前端·javascript·css·vue.js·uni-app·html