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 语言导览中找到有关展开运算符语法的更多详细信息。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坚果的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值