如果没有初始值,可以变成任何类型
var a;
// var a = ""; // 一旦赋值,就确定类型,不能随意改动
a = 'ducafecat';
a = 123;
a = true;
a = {'key': 'val123'};
a = ['abc'];
print(a);
动态任意类型
编译阶段检查类型
Object a = 'doucafecat';
a = 123;
a = [2222];
a.p();
动态任意类型
编译阶段不检查检查类型
dynamic a = 'doucafecat';
a = 123;
a = [1111];
a.p();
唯一区别 var 如果有初始值,类型被锁定
var a = 'ducafecat';
dynamic a = 'doucafecat';
Object a = 'doucafecat';
a = 123;
声明后,类型被锁定
String a;
a = 'ducafecat';
a = 123;
名称 | 说明 |
---|---|
num | 数字 |
int | 整型 |
double | 浮点 |
bool | 布尔 |
String | 字符串 |
StringBuffer | 字符串 buffer |
DateTime | 时间日期 |
Duration | 时间区间 |
List | 列表 |
Sets | 无重复队列 |
Maps | kv 容器 |
enum | 枚举 |
String a = 'doucafecat';
int i = 123;
double d = 0.12;
bool b = true;
DateTime dt = new DateTime.now();
List l = [ a, i, d, b, dt];
变量声明后默认都是 null
var a;
String a;
print(a);
assert(a == null);
assert
检查点函数,如果不符合条件直接抛出错误并终止程序进程
不用明确变量类型
var map = <String, dynamic>{};
map["image"] = image;
map["title"] = title;
map["desc"] = desc;
这里不用
var
,就要写成Map<String, dynamic>
api 查询通用接口封装的时候,我们一般用动态类型
如一个 api 请求
Future<Response<T>> get<T>(
String path, {
Map<String, dynamic> queryParameters,
...
});
Map<String, dynamic>? queryParameters
, 查询参数值是动态
如分类实例定义
class Category {
int id; // 数字 id
String name; // 字符串 分类名称
String slug;
Category({this.id, this.name, this.slug});
...
}
int id;
String name;
明确类型
final String a = 'ducafecat';
final a = 'ducafecat';
const String a = 'ducafecat';
const a = 'ducafecat';
final a = 'ducafecat';
a = 'abc';
const a = 'ducafecat';
a = 'abc';
final var a = 'ducafecat';
const var a = 'ducafecat';
final dt = DateTime.now();
const dt = const DateTime.now();
final List ls = [11, 22, 33];
ls[1] = 44;
const List ls = [11, 22, 33];
ls[1] = 44;
final a1 = [11 , 22];
final a2 = [11 , 22];
print(identical(a1, a2));
const a1 = [11 , 22];
const a2 = [11 , 22];
print(identical(a1, a2));
identical
通过比较两个引用的是否是同一个对象判断是否相等
class PlaceholdWidget extends StatelessWidget {
final String? assetImagePath;
const PlaceholdWidget({
Key? key,
this.assetImagePath,
}) : super(key: key);
@override
Widget build(BuildContext context) {
...
}
}
// 本地存储key
static const storageFirstOpen = 'first_open';
static const storageLanguageCode = 'language_code';
static const storageThemeCode = 'theme_code';
static const storageToken = 'token';
static const storageProfile = 'profile';
// string -> int
// string -> double
int a = int.parse('123');
double b = double.parse('1.223');
// int -> string
// double -> string
String a = 123.toString();
String b = 1.223.toString();
print([a, b]);
// double -> int
double a = 1.8;
int b = a.toInt();
print(b);
为了代表布尔值,Dart 有一个名字为 bool 的类型。 只有两个对象是布尔类型的:true 和 false 所创建的对象, 这两个对象也都是编译时常量。
bool a;
print(a);
只有 true 对象才被认为是 true。 所有其他的值都是 flase。
String name = 'ducafecat';
if(name) {
print('this is name');
}
var a = true;
assert(a);
var name = '';
assert(name.isEmpty);
assert(name.isNotEmpty);
var num = 0 / 0;
assert(num.isNaN);
注意: 断言只在检查模式下运行有效,如果在生产模式 运行,则断言不会执行。
&&
逻辑与bool a = true;
bool b = true;
assert(a && b);
||
逻辑或bool a = true;
bool b = false;
assert(a || b);
!
逻辑非bool a = true;
bool b = !a;
print(b);
==
等于if(a == b) {}
!=
不等于if(a != b) {}
>
大于if(a > b) {}
>=
大于或等于if(a >= b) {}
<
小于if(a < b) {}
<=
小于或等于if(a <= b) {}
String a = 'ducafecat';
String b = "ducafecat";
String a = 'ducafecat';
String b = "ducafecat";
String a = 'ducafecat';
String b = "ducafecat";
var a = 'hello' + ' ' + 'ducafecat';
var a = 'hello'' ''ducafecat';
var a = 'hello' ' ' 'ducafecat';
var a = 'hello'
' '
'ducafecat';
var a = '''
hello word
this is multi line
''';
var a = """
hello word
this is multi line
""";
print(a);
var a = 'web site ducafecat.tech';
print(a.contains('ducafecat'));
print(a.startsWith('web'));
print(a.endsWith('tech'));
print(a.indexOf('site'));
true
true
true
var a = 'web site ducafecat.tech';
print(a.substring(0,5));
var b = a.split(' ');
print(b.length);
print(b[0]);
web s
3
web
var now = new DateTime.now();
print(now);
2022-05-28 20:04:43.607
var now = new DateTime.now();
print(now);
2022-05-28 20:04:43.607
print('hello word word!'.replaceAll('word', 'ducafecat'));
hello ducafecat ducafecat!
var now = new DateTime.now();
print(now);
2022-05-28 20:04:43.607
var d = new DateTime(2018, 10, 10, 9, 30);
print(d);
2018-10-10 09:30:00.000
var d = new DateTime.utc(2018, 10, 10, 9, 30);
print(d);
2018-10-10 09:30:00.000Z
var d1 = DateTime.parse('2018-10-10 09:30:30Z');
print(d1);
2018-10-10 09:30:30.000Z
var d2 = DateTime.parse('2018-10-10 09:30:30+0800');
print(d2);
2018-10-10 01:30:30.000Z
var d1 = DateTime.now();
print(d1);
print(d1.add(new Duration(minutes: 5)));
print(d1.add(new Duration(minutes: -5)));
2022-05-28 22:09:12.805
2022-05-28 22:14:12.805
2022-05-28 22:04:12.805
var d1 = new DateTime(2018, 10, 1);
var d2 = new DateTime(2018, 10, 10);
print(d1.isAfter(d2));
print(d1.isBefore(d2));
false
true
var d1 = DateTime.now();
var d2 = d1.add(new Duration(milliseconds: 30));
print(d1.isAtSameMomentAs(d2));
false
var d1 = new DateTime(2018, 10, 1);
var d2 = new DateTime(2018, 10, 10);
var difference = d1.difference(d2);
print([difference.inDays, difference.inHours]);
[-9, -216]
var now = new DateTime.now();
print(now.millisecondsSinceEpoch);
print(now.microsecondsSinceEpoch);
1653747090687
1653747090687000
key value 形式的集合,也叫键值对。
var a = {'name': 'ducafecat', 'web': 'www.ducafecat.tech'};
print(a);
{name: ducafecat, web: www.ducafecat.tech}
var a = Map();
a['name'] = 'ducafecat';
a['web'] = 'www.ducafecat.tech';
a[0] = 'abc';
a[0] = '1231231';
print(a);
{name: ducafecat, web: www.ducafecat.tech, 0: 1231231}
key 相同,覆盖数据
var a = Map<int, String>();
a[0] = 'java';
a[1] = 'python';
print(a);
{0: java, 1: python}
名称 | 说明 |
---|---|
isEmpty | 是否为空 |
isNotEmpty | 是否不为空 |
keys | key 集合 |
values | values 集合 |
length | 个数 |
entries | 加工数据入口 |
var a = {'name': 'ducafecat', 'web': 'www.ducafecat.tech'};
print(a.isEmpty);
print(a.isNotEmpty);
print(a.keys);
print(a.values);
print(a.length);
print(a.entries);
false
true
(name, web)
(ducafecat, www.ducafecat.tech)
2
(MapEntry(name: ducafecat), MapEntry(web: www.ducafecat.tech))
名称 | 说明 |
---|---|
addAll | 添加 |
addEntries | 从入口添加 |
containsKey | 按 key 查询 |
containsValue | 按 value 查询 |
clear | 清空 |
remove | 删除某个 |
removeWhere | 按条件删除 |
update | 更新某个 |
updateAll | 按条件更新 |
新增 kv 数据
b.addAll({'first': 'java', 'second': 'python'});
接入另一个 map 集合
b.addEntries(a.entries);
检查 key 是否存在
print(a.containsKey('name'));
检查 value 是否存在
print(a.containsValue('www.ducafecat.tech'));
清空数据
b.clear();
删除数据
a.remove('name');
按条件删除
a.removeWhere((key,val) => key == 'name');
更新数据
a.update('name', (val) => 'abc');
更新批量
a.updateAll((key, val) => "---$val---");
名称 | 说明 |
---|---|
[] | 取值 |
[]= | 赋值 |
print(a['name']);
a['name'] = 'abc';
Set
是一个元素唯一的有序队列
var a = Set();
a.add('java');
a.add('php');
a.add('python');
a.add('java');
a.add('sql');
a.add('swift');
a.add('dart');
print(a);
{java, php, python, sql, swift, dart}
b.addAll(['dart', 'c#', 'j#', 'e#']);
print(b);
{dart, c#, j#, e#}
var ls = ['dart', 'java', 'c#', 'j#', 'e#', 'java'];
var tags = Set();
tags.addAll(ls);
print(tags);
print(tags.toList());
{dart, java, c#, j#, e#}
[dart, java, c#, j#, e#]
名称 | 说明 |
---|---|
isEmpty | 是否为空 |
isNotEmpty | 是否不为空 |
first | 第一个 |
last | 最后一个 |
length | 个数 |
名称 | 说明 |
---|---|
addAll | 添加 |
contains | 查询单个 |
containsAll | 查询多个 |
difference | 集合不同 |
intersection | 交集 |
union | 联合 |
lookup | 按对象查询到返回对象 |
remove | 删除单个 |
removeAll | 删除多个 |
clear | 清空 |
firstWhere | 按条件正向查询 |
lastWhere | 按条件反向查询 |
removeWhere | 按条件删除 |
retainAll | 只保留几个 |
retainWhere | 按条件只保留几个 |
// b.addAll(['dart', 'c#', 'j#', 'e#']);
// print(b.contains('dart'));
// print(b.containsAll(['dart', 'swift']));
// print('b => $b');
// print(a.difference(b));
// print(a.intersection(b));
// print(b.lookup('dart'));
// print(b.union(a));
// b.remove('dart');
// b.removeAll(['dart','c#']);
// b.clear();
// print(b.firstWhere((it) => it == 'c#'));
// print(b.lastWhere((it) => it == 'c#'));
// b.removeWhere((it) => it == 'c#');
// b.retainAll(['e#']);
// b.retainWhere((it) => it == 'e#');
// b.retainWhere((it) {
// bool ret = it == 'e#';
// return ret;
// });
var fd = <String>{"js", "node", "dart", "css", "html", "macos", "docker", "git"};
var ed = <String>{"linux", "docker", "git", "go", "python", "sql", "node", "js", "aws"};
print(fd.intersection(ed));
{js, node, docker, git}
var fd = <String>{"js", "node", "dart", "css", "html", "macos", "docker", "git"};
var ed = <String>{"linux", "docker", "git", "go", "python", "sql", "node", "js", "aws"};
print(fd.union(ed));
{js, node, dart, css, html, macos, docker, git, linux, go, python, sql, aws}
适合用在常量定义,类型比较很方便。
// 定义颜色枚举值
enum ColorType {
none,
red,
green,
blue,
}
void main(List<String> args) {
// 1 接收输入值 red 字符串
var input = "red";
// 2 将输入值转换为 ColorType 枚举类型
var color = ColorType.none;
if (input == "red") {
color = ColorType.red;
} else if (input == "green") {
color = ColorType.green;
} else if (input == "blue") {
color = ColorType.blue;
}
// 3 switch 判断,打印输出
switch (color) {
case ColorType.red:
print(ColorType.red);
break;
case ColorType.green:
print(ColorType.green);
break;
case ColorType.blue:
print(ColorType.blue);
break;
default:
print(ColorType.none);
}
}
定义发帖类型 视频 图片 空
enum PostType { video, image, none }
业务中判断
PostType get type {
if (detail.type == POST_TYPE_IMAGE) {
return PostType.image;
} else if (detail.type == POST_TYPE_VIDEO) {
return PostType.video;
} else {
return PostType.none;
}
}
...
if (type == PostType.video && !_hasDetail) {
playlist.insert(0, VideoMedia(detail));
}
...
if (type == PostType.video) {
if (playlist.isEmpty) {
playlist.add(VideoMedia(detail));
} else {
playlist.first.post = detail;
}
}
} finally {
_isLoading = false;
if (type == PostType.video && !_hasDetail) getPostList();
}
int add(int x) {
return x + 1;
}
调用
add(1);
int add(int x, [int? y, int? z]) {
if (y == null) {
y = 1;
}
if (z == null) {
z = 1;
}
return x + y + z;
}
调用
add(1, 2);
int add(int x, [int y = 1, int z = 2]) {
return x + y;
}
调用
int(1, 2);
int add({int x = 1, int y = 1, int z = 1}) {
return x + y + z;
}
调用
int(x: 1, y: 2);
void main(){
int add(int x){
return x + x;
}
print(add(1));
}
Function makeAdd(int x) {
return (int y) => x + y;
}
调用
var add = makeAdd(1);
print(add(5));
下面代码定义了只有一个参数 item 且没有参数类型的匿名方法。 List 中的每个元素都会调用这个函数,打印元素位置和值的字符串:
const list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
print('${list.indexOf(item)}: $item');
});
箭头函数 如果只有一个表达式
list.forEach((item) => print('${list.indexOf(item)}: $item'));
下面是一个嵌套函数中变量在多个作用域中的示例:
bool topLevel = true;
void main() {
var insideMain = true;
void myFunction() {
var insideFunction = true;
void nestedFunction() {
var insideNestedFunction = true;
assert(topLevel);
assert(insideMain);
assert(insideFunction);
assert(insideNestedFunction);
}
}
}
注意 nestedFunction() 函数可以访问包括顶层变量在内的所有的变量。
bool isPrint = true;
if (isPrint) {
print('hello');
}
for (var i = 0; i < 5; i++) {
print(i);
}
bool isDone = false;
while(!isDone) {
print('is not done');
isDone = true;
}
bool isRunning = true;
do {
print('is running');
isRunning = false;
} while (isRunning);
String name = 'cat';
switch (name) {
case 'cat':
print('cat');
break;
default:
print('not find');
}
num i = 1;
while(true) {
print('${i} - run');
i++;
if(i == 5) {
break;
}
}
for (var i = 0; i < 5; i++) {
if (i < 3) {
continue;
}
print(i);
}
String command = "close";
switch (command) {
case "open":
print("open");
break;
case "close":
print("close");
continue doClear;
case "close2":
print("close2");
continue doClear;
doClear:
case "doClose":
print("doClose");
break;
default:
print("other");
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。