首页 > 技术文章 > Dart 基本数据类型与类型归属判断【转】

KillBugMe 2020-09-02 14:35 原文

一、基本变量类型

dart 以 main 函数作为执行入口,虽然不强制类型,但是建议使用强制类型来使用,编译器不需要去推导类型:

如果使用var声明变量,则不会进行类型约束

void main() {

}

1、 变量声明 & console 输出 & 字符串拼接 & 数字转字符串

  print('hello world!');
  var firstName = 'post';
  String lastName = 'bird';
  var age = 122;
  print(firstName + lastName + ' , age is ' + age.toString());


  var name = 'ptbird';
  name = 123.toString();
  int num = 3;
  double num2 = 0.111;
  print( num ++ );
  print( ++ num );
  print(num2 / num);

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
hello world!
postbird , age is 122
3
5
0.0222

2、const 变量和 final 变量声明

const 只能通过静态数据赋值,否则会报错

  const lastName = 'postbird';
  final firstName = 'bird  ';
  // lastName = '123';  // 报错
  // firstName = '123'; // 报错
  final time = new DateTime.now();
  // const time2 = new DateTime.now(); // 报错

输出结果(无输出)


[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"

[Done] exited with code=0 in 1.167 seconds

如果给 final 或者 const 再次赋值了,则会报错如下:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
demo1/demo1.dart:20:3: Error: Setter not found: 'lastName'.
  lastName = '123';
  ^^^^^^^^

[Done] exited with code=254 in 2.262 seconds

如果给 const 赋值非 const 变量,则报错如下:

 // const time2 = new DateTime.now(); // 报错
[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
demo1/demo1.dart:23:17: Error: New expression is not a constant expression.
  const time2 = new DateTime.now();
                ^^^

[Done] exited with code=254 in 2.992 seconds

3、String 字符串换行和字符串拼接

1)换行''' '''

  String content = '''
    multipart
    ...
    string
  ''';  
  print(content);

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
    multipart
    ...
    string

2)字符串拼接

拼接除了使用加好,还可以像 js 的模板字符串直接拼接,语法差不多,只不过不需要反引号,普通引号即可,${v},其中如果只是变量名,可以省略大括号$v

  String str1 = 'dart1';
  String str2 = 'darg2';
  int age = 21;
  print('$str1   $str2  ${age.toString()}');
  print('${str1}   ${str2}  ${age.toString()} ${age} ${age * age}');

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
dart1   darg2  21
dart1   darg2  21 21 441

[Done] exited with code=0 in 2.336 seconds

4、int 和 double 数字 整形和浮点型

  int num1 = 123;
  double price = 123.452323232;
  print(price * num1);
  price = 12;
  print(price * num1);

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
15184.635757536
1476.0

[Done] exited with code=0 in 2.772 seconds

5、bool 类型和 if 判断

if 判断只能是 bool 类型的返回值,这点和 js 这衶弱类型语言完全不同:

  bool flag = true;
  if(flag) {
    print('--- true');
  }
  int num1 = 1;
  double num2 = 1.0;
  String num3 = '1';
  if(num1 == num2) {
    print('num1 == num2');
  } else {
    print('num1 != num2');
  }
  if(num1 == num3) {
    print('num1 == num3');
  } else {
    print('num1 != num3');
  }
  // int a = 1;
  // if(a) {  // 报错
  //   print('true');
  // }

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
--- true
num1 == num2
num1 != num3

[Done] exited with code=0 in 1.452 seconds

如果 if 使用了非 bool 类型判断报错如下:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
demo1/demo1.dart:65:6: Error: A value of type 'int' can't be assigned to a variable of type 'bool'.
Try changing the type of the left hand side, or casting the right hand side to 'bool'.
  if(a) {
     ^

[Done] exited with code=254 in 1.974 seconds

6、List 类型

List 类型是使用非常多的类型,与 js 的 Array 类似,初始赋值可以直接给一个列表,也可以通过new List()指定空的列表.

默认列表子项支持的值类型是 dynamic,不限制具体类型,如果需要限制具体类型则需要使用泛型,比如new List<String>()限制子项类型

List 作为对象提供了一些的方法和属性: API 文档地址:https://api.dart.dev/dev/2.4.0-dev.0.0/dart-core/List-class.html

通过add()能够添加一个子项, 通过addAll()能够追加另一个 List

  List l1 = [123, '123', 'postbird'];
  print(l1);
  List l2 = new List();
  l2.add('abc');
  l2.add(123);
  l2.addAll(['iterable', '222', '333', 123]);
  print(l2);
  List l3 = new List<String>();
  l3.add('abc');
  // l3.add(123);
  print(l3);
  List l4 = new List<int>();
  l4.add(123);
  // l4.add(123.12);
  print(l4);
  List l5 = new List<int>();
  l5.add(1);
  l5.add(3);
  l5.add(2);
  l5.add(4);
  l5.add(6);
  l5.add(2);
  print(l5);
  l5.sort();
  print(l5);

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
[123, 123, postbird]
[abc, 123, iterable, 222, 333, 123]
[abc]
[123]
[1, 3, 2, 4, 6, 2]
[1, 2, 2, 3, 4, 6]

[Done] exited with code=0 in 2.079 seconds

7、Map 类型

与 javascript 对象类似,在 oc 中称为字典。

可以通过字面量指定,也可以通过声明一个new Map()的空 Map。

API 文档地址:https://api.dart.dev/dev/2.4.0-dev.0.0/dart-core/Map-class.html

  var person = {
    'name': 'ptbird',
    'age': 24,
    'work': ['it1', 'it2']
  };
  print(person);
  print(person.toString());
  print(person['name']);
  print(person['age']);
  print(person['work']);
  Map person2 = new Map();
  person2['name'] = 'name2';
  person2['age'] = 24;
  person2['work'] = ['it1', 'it2'];
  print(person2);
  print(person2['work']);

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
{name: ptbird, age: 24, work: [it1, it2]}
{name: ptbird, age: 24, work: [it1, it2]}
ptbird
24
[it1, it2]
{name: name2, age: 24, work: [it1, it2]}
[it1, it2]

[Done] exited with code=0 in 1.584 seconds

8、类型判断

is操作符能够判断类型归属,比如A is B,能够返回 bool 类型,判断 A 是否属于 B 类型。

  var value = 123;
  if(value is String) {
    print('${value} is string');
  } else if (value is int) {
    print('${value} is int');
  } else if (value is double) {
    print('${value} is double');
  } else {
    print('${value} is other type');
  }

输出结果:

[Running] dart "e:\Aprojects\DartHelloWorldDemo\demo1\demo1.dart"
123 is int

[Done] exited with code=0 in 1.567 seconds

来源:http://www.ptbird.cn/dart-variable-operation.html

推荐阅读