Dart 入门教程(一),变量、集合篇

这是 Dart 入门教程,我总结在这,以后有需要可以自查,本篇主要是数据类型。

声明变量

Dart 主要有两种声明变量的方法,一种是明确声明,其次是类型推导。

  //明确声明变量
  String name = "hello";
  int i = 100;
  double d = 100.3;
  bool b = true;
  
  //类型推导(var/final/const)
  var age = 18;
  final address = "深圳市";
  const size = 18;

关键是要学习 finalconst 的区别。

  //final可以运行期间才确定值,可以用过计算和传入方式赋值
  //const必须在编译期间确定值,必须是常量值
  const date1 = DateTime.now(); //error
  final date2 = DateTime.now();

它俩比较,const 的使用场景太少了,其实我们更多用的是 final 。还有一种特殊情况,我们使用 final 定义属性后,如果想修改属性的值,这该怎么办呢?这也是一个很常见的需求。比如我这定义了一个对象 Pen

class Pen{
  final String? color;
  
  Pen({this.color});
  
  Pen copyWith({String? color}){
    return Pen(color: color ?? this.color);
  }
}

除了构造方法,我还实现了一个 copyWith 函数,它的作用就是修改 final 定义的属性值。

  var pen = Pen(color: "蓝色");
  print(pen.color); // 输出 蓝色
  pen = pen.copyWith(color: "黄色");
  print(pen.color); // 输出 黄色

类型互转

Dart 数据类型主要分为三种:数字类型(int、double)、字符串类型(String)、布尔类型(bool)。下面是互相转换的案例。

将 int 转换成 double

  int myInt = 5;
  double myDouble = myInt.toDouble();
  print(myDouble); // 输出 5.0

将 double 转换成 int

  double myDouble = 5.7;
  int myInt = myDouble.toInt();
  print(myInt); // 输出 5

将 int 、double 转换成字符串

  int myInt = 5;
  String myString = myInt.toString();
  print(myString); // 输出 "5"

  double myDouble = 3.14;
  String myString = myDouble.toString();
  print(myString); // 输出 "3.14"

这里还有种常见需求,就是使用 toString() 方法时可以传递一个参数,用于指定输出字符串的格式。例如,可以指定输出字符串的小数位数或填充字符。比如我只想保留小数的两位有效数字,并且想四舍五入截取小数。

  double myDouble = 3.1459265359;
  String myString = myDouble.toStringAsFixed(2); // 指定小数位数为 2
  print(myString); // 输出 "3.15"

将字符串转换成 double

  String myString = '3.14';
  double myDouble = double.parse(myString);
  print(myDouble); // 输出 3.14

将字符串转换成 int

  String myString = '5';
  int myInt = int.parse(myString);
  print(myInt); // 输出 5

字符串拼接

这一部分其实我在如何在 Dart 中拼接字符串已经分享过,这里就简单列一下案例。

使用 + 操作符连接字符串:

  String firstName = 'John';
  String lastName = 'Doe';
  String fullName = firstName + ' ' + lastName;
  print(fullName); // 输出 "John Doe"

使用插值表达式($variableName${expression})插入变量或表达式的值:

  String firstName = 'John';
  String lastName = 'Doe';
  int age = 30;
  String fullName = '$firstName $lastName';
  String message = 'My name is $fullName and I am $age years old.';
  print(message); // 输出 "My name is John Doe and I am 30 years old."

更多使用常见推荐看上面的文章。

集合

这里我把 Dart 中的 List、Set、Map 统称集合,当然,这三种的定义和构造方法都不一样。

List 是有序,可以重复的元素集合。

  void main() {
    List<String> fruits = ['apple', 'banana', 'orange', 'apple'];
    print(fruits); // 输出:['apple', 'banana', 'orange', 'apple']
  }

Set 和 List 相反,无序,并且不能包含重复元素的集合,所以它的使用场景基本就俩,要么用来去重,要么就是快速查找唯一元素。

  void main() {
    Set<String> uniqueFruits = {'apple', 'banana', 'orange', 'apple'};
    print(uniqueFruits); // 输出:{apple, banana, orange}
    
    List<String> fruitsWithDuplicates = ['apple', 'banana', 'orange', 'apple', 'banana'];
    Set<String> uniqueFruitsSet = Set.from(fruitsWithDuplicates);
    print("去重后的列表:$uniqueFruitsList"); 
    ---
    去重后的列表:[apple, banana, orange]
  }

Map 是无序的键值对集合,这个键(Key)可以是字符串也可以是数字,通过这个键来存取值。

  void main() {
    Map<String, int> fruitPrices = {
      'apple': 2,
      'banana': 1,
      'orange': 3,
    };
    print(fruitPrices); // 输出:{apple: 2, banana: 1, orange: 3}
  }

集合转换

从 List 到 Set:

  void main() {
    List<String> fruits = ['apple', 'banana', 'orange', 'apple'];
    Set<String> uniqueFruits = Set.from(fruits);
    print(uniqueFruits); // 输出:{apple, banana, orange}
  }

从 Set 到 List:

  void main() {
    Set<String> uniqueFruits = {'apple', 'banana', 'orange'};
    List<String> fruits = List.from(uniqueFruits);
    print(fruits); // 输出:[apple, banana, orange]
  }

从 Map 到 List(只取键或值):

  void main() {
    Map<String, int> fruitPrices = {
      'apple': 2,
      'banana': 1,
      'orange': 3,
    };
    List<String> fruitNames = List.from(fruitPrices.keys);
    List<int> prices = List.from(fruitPrices.values);

    print(fruitNames); // 输出:[apple, banana, orange]
    print(prices); // 输出:[2, 1, 3]
  }

OK,这是 Dart 的属性,接下来是函数,也就是 Dart 语法第二篇。

Dart 入门教程(一),变量、集合篇

Dart 入门教程(二),函数篇

Dart 入门教程(三),运算符篇

Dart 入门教程(四),类的使用

Dart 入门教程(五),同步和异步

本文由老郭种树原创,转载请注明:https://guozh.net/dart-getting-started-tutorial-variable/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注