ui知识点

2.1、Dart语言基础:变量、运算符、流程控制

2021-10-08  本文已影响0人  双鱼子曰1987

学习笔记,旨在于快速入门和学习Dart,其中可能会有理解错误,请指出,一起学习。

系列文章

2.1、Dart语言基础:变量、运算符
2.2、Dart语言基础:函数与闭包
2.3、Dart语言基础:面向对象
2.4、Dart语言基础:异步
2.5、Dart语言基础:库与包
...

一、概述

参考:
dart英文官网
Dart 中文教程
dart-源码api

特性

重要概念

var age = 10; // 类型推导为int
age = "xxx"; // 给int类型的变量 赋值 字符串报错
print(age);
int? aNullableInt = null;

如果变量确定一定有值,可以使用!(如果为空,则会抛出异常)。

int x = nullableButNotNullInt!
void sayHelloworld(String name) {
  print("$name say hello!"); //${name}
}
void main(List<String> arguments)  { ... }

二、基础


0、基本格式

// 检查空字符串。
var fullName = '';
assert(fullName.isEmpty);

// 检查 0 值。
var hitPoints = 0;
assert(hitPoints <= 0);

// 检查 null 值。
var unicorn;
assert(unicorn == null);

// 检查 NaN 。
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);

1、变量与常量

1.1、变量

Dart万物结尾对象,因此变量实际就是一个引用。

1.1.1、声明方式
1.1.2、变量声明是否可以为空?
  //  Error: Non-nullable variable 'obj' must be assigned before it can be used.
  Object obj;
  print(obj);

  // Error: Non-nullable variable 'nickName' must be assigned before it can be used.
  String nickName;
  print(nickName); 

  // Error: Non-nullable variable 'age' must be assigned before it can be used.
  int age;
  print(age);
  // 初始化可以不指定类型,值为null
  dynamic nickName;
  print(nickName);

  var name;
  print(name);

  String? nickName1;
  print(nickName1);
1.1.3、延迟变量,关键字late(Dart 1.6新加)
// late的特性:
Lazily initializing a variable. 
Declaring a non-nullable variable that’s initialized after its declaration.

// late的使用场景
This lazy initialization is handy in a couple of cases:
1、The variable might not be needed, and initializing it is costly.
2、You’re initializing an instance variable, and its initializer needs access to this.
late String description;

void main() {
  description = 'Feijoada!';
  print(description);
}
// 如果temperature没有被使用,则函数 _readThermometer 不会调用
late String temperature = _readThermometer(); 

1.2、常量

// Error: Can't assign to the final variable 'name'.
final String name = 'hello';
name = 'new hello';
  // Error: Can't assign to the const variable 'name'.
  const String name = 'hello';
  name = 'new hello';
1.2.1、变量 以及 变量本身 均不允许被修改
  // Error: Can't assign to the const variable 'list'.
  const list = [1, 2, 3];
  list = [11, 12];

  // Unsupported operation: Cannot modify an unmodifiable list
  list[0] = 10;
  print(list);
  // 此时,list推导的类型为不可变数组,修改字典值报错;
  var list = const [1,2,3];
  list[0] = 10;  // 报错Unsupported operation: Cannot modify an unmodifiable list
  
// 但是变量list可以被重新初始化赋值
  list = [1, 2, 3];
  print(list);

  list[0] = 10;
  print(list);

3、内置类型

3.1、专有变量
image.png
3.2、数值类型,关键字num,可以是int和double
  num val = 1;
  print(val); // 1

  val += 0.5;
  print(val); // 1.5
  bool flag = false;
  print(flag);
  flag = true;
  print(flag);
3.3、数组,关键字List
var list = [1, 2, 3];
list[0] = 0;
list.length;

// C语言,大括号
int arr1[3] = {1, 2, 3};

常用APIs:

void testListTypeDemo() {
  var fruits = [];
  print('isEmpty:${fruits.isEmpty}');

  fruits.add('apples');
  fruits.addAll(['pear', 'banana']);
  print('原数组:$fruits');
  print('first:${fruits.first}, last:${fruits.last}');
  print('length:${fruits.length}');
  print('indexOf: ${fruits.indexOf('banana')}');
  print("contain:${fruits.contains('apples')}");
  print("join:${fruits.join('、 ')}");

  fruits.insert(0, 'watermalon');
  print('原数组:$fruits');

  print('range:${fruits.getRange(0, 2)}');

  fruits.remove('apples');
  fruits.removeAt(0);
  print(fruits);

  fruits.clear();
  print(fruits);

  var list = List.filled(8, 'name');
  print(list);

  var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
  print('原数组:$numbers');
  numbers.sort((a, b) => a>b?a:b);
  print('倒叙:$numbers');
}
  var list = [1, 2, 3];
  var list2 = [0, ...list];
  print(list2); // [0, 1, 2, 3]

  var null_list;
  var list3 = [0, ...?null_list]; // 可为空
  print(list3); // [0]
  bool promoActive = true;
  var nav = ['Home', 'Furniture', 'Plants', if (promoActive) 'Outlet'];
  print(nav); // [Home, Furniture, Plants, Outlet]

  var listOfInts = [1, 2, 3];
  var listOfStrings = ['#0', for (var i in listOfInts) '#$i'];
  print(listOfStrings); // [#0, #1, #2, #3]
3.4、集合,关键字Set,(无序,大括号定义)
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
var elements = <String>{};
elements.add('fluorine');
elements.addAll(halogens);
  final constantSet = const {
    'fluorine',
    'chlorine',
    'bromine',
    'iodine',
    'astatine',
  };
3.5、字典,关键字Map
// Map<String, String>
var gifts = {
  // Key:    Value
  'first': 'partridge',
  'second': 'turtledoves',
  'fifth': 'golden rings'
};
3.6、标识符,Symbol
# label_1
# label_x

4、流程控制

if (cond1) {
    
} else if (cond2) {
    
} else {
    
}
for (int i=0; i<8; i++) {
    print(i);
}

// for-in
for (var object in flybyObjects) {
  print(object);
}
while(1) {
    
}

do {
    
} while(1)

switch/case

var command = 'CLOSED';
switch (command) {
  case 'OPEN': //非空case,必须跟break
    executeOpen();
    break;

  case 'CLOSED': // 空 case ,支持falls-through.
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}
var command = 'CLOSED';
switch (command) {
  case 'CLOSED':
    executeClosed();
    continue nowClosed;
  // Continues executing at the nowClosed label.

  nowClosed:
  case 'NOW_CLOSED':
    // Runs for both CLOSED and NOW_CLOSED.
    executeNowClosed();
    break;
}

5、运算符

5.1、基本
assert(5 / 2 == 2.5); // 结果是双浮点型
assert(5 ~/ 2 == 2); // 结果是整型
5.2、空合运算符??
// 如果b为空时,将变量赋值给b,否则,b的值保持不变。
b ??= value;
5.3、类型判定运算符
5.4、级联运算符 ..

可以实现对同一个对像进行一系列的操作。

querySelector('#confirm') // 获取对象。
  ..text = 'Confirm' // 调用成员变量。
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));

// 等价于
var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));
上一篇 下一篇

猜你喜欢

热点阅读