从 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类型变量) {// 处理数据}
相关推荐
kyriewen14 小时前
我手写了一个 EventEmitter,面试官追问了 6 个问题——第 4 个我没答上来
前端·javascript·面试
山河木马15 小时前
矩阵专题2-怎么创建视图矩阵(uViewMatrix)
javascript·webgl·计算机图形学
tangdou36909865516 小时前
AI真好玩系列-2分钟快速了解DeepAgents | Quick Guide to DeepAgents in 2 Minutes
前端·javascript·后端
张元清16 小时前
React useIntersectionObserver Hook:懒加载与可见性检测(2026)
javascript·react.js
彭于晏爱编程16 小时前
纯 JS + Node,一个下午手搓了能读懂公司代码的 AI 助手,老板以为我转行了
前端·javascript
妙码生花17 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十四):眨眼小人登录页制作
前端·javascript·ai编程
妙码生花17 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十三):前端路由初始化
前端·javascript·ai编程
PBitW18 小时前
GPT训练我的第四天,被打惨了!!!😭😭😭
前端·javascript·面试
DarkLONGLOVE18 小时前
快速上手 Pinia!Vue3 极简状态管理使用教程
javascript·vue.js
mackbob18 小时前
.eslintrc.js详细配置说明
javascript