dart使用技巧集合

Flutter/Dart:生成最小值和最大值之间的随机数

在 Dart(以及 Flutter)中生成给定范围内的随机整数的几个示例。

示例 1:使用 Random().nextInt() 方法

import 'dart:math';

randomGen(min, max) {
  // the nextInt method generate a non-ngegative random integer from 0 (inclusive) to max (exclusive)
  var x = Random().nextInt(max) + min;

  // If you don't want to return an integer, just remove the floor() method
  return x.floor();
}

void main() {
  int a = randomGen(1, 10);
  print(a);


}

输出:

8 // you may get 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

您得到的结果可能包含最小值、最大值或此范围内的值。

示例 2:使用 Random.nextDouble() 和 floor() 方法

编码:

import 'dart:math';

randomGen(min, max) {
  // the nextDouble() method returns a random number between 0 (inclusive) and 1 (exclusive)
  var x = Random().nextDouble() * (max - min) + min;

  // If you don't want to return an integer, just remove the floor() method
  return x.floor();
}

// Testing
void main() {
  // with posstive min and max
  print(randomGen(10, 100));
  
  // with negative min 
  print(randomGen(-100, 0));
}

输出(输出当然是随机的,每次重新执行代码时都会改变)。

47
-69

您得到的结果可能会包含 min 但绝不会包含 max。

如何在 Dart 中对数字进行四舍五入

为了在 Dart 中对数字进行四舍五入,我们可以使用**round()**方法。此方法返回与输入数字最接近的整数。如果无法确定最接近的整数(例如 0.5、-2.5、3.5 等),则从零舍入。

例子:

import 'package:flutter/foundation.dart';

void main() {
  var x = 10.3333;
  if (kDebugMode) {
    print(x.round());
  }

  var y = -1.45;
  if (kDebugMode) {
    print(y.round());
  }

  var z = 4.55;
  if (kDebugMode) {
    print(z.round());
  }

  var t = 1.5;
  if (kDebugMode) {
    print(t.round());
  }
}

输出:

10
-1
5
2

您可以在官方文档中找到有关 round() 方法的更多信息。

在 Dart 中合并 2 个列表

使用加法 (+) 运算符

例子:

void main() {
  final List list1 = [1, 2, 3];
  final List list2 = [4, 5, 6];
  final List list3 = list1 + list2;
  print(list3);
}

输出:

[1, 2, 3, 4, 5, 6]

使用列表 addAll() 方法

Dart的List类提供了addAll方法,可以帮助您轻松地将 2 个列表连接在一起。

例子:

void main() {
  List listA = [1, 2, 3];
  List listB = [4, 5, 6];
  listA.addAll(listB);
  print(listA);
  
  List<String> listC = ['Dog', 'Cat'];
  List<String> listD = ['Bear', 'Tiger'];
  listC.addAll(listD);
  print(listC);
}

输出:

[1, 2, 3, 4, 5, 6]
[Dog, Cat, Bear, Tiger]

您可以在官方文档中找到有关 addAll() 方法的更多信息。

使用Spread运算符

例子:

void main() {
  final List list1 = ['A', 'B', 'C'];
  final List list2 = ['D', 'E', 'F'];
  final List list3 = [...list1, ...list2];
  print(list3);
}

输出:

[A, B, C, D, E, F]

您可以在Dart 语言导览中找到有关展开运算符语法的更多详细信息。

猜你喜欢

转载自blog.csdn.net/qq_39132095/article/details/125326640