1. 程式人生 > 實用技巧 >Dart 基本資料型別與型別歸屬判斷【轉】

Dart 基本資料型別與型別歸屬判斷【轉】

一、基本變數型別

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