dart使用技巧集合

举报
坚果的博客 发表于 2022/06/17 12:43:40 2022/06/17
【摘要】 Flutter/Dart:生成最小值和最大值之间的随机数在 Dart(以及 Flutter)中生成给定范围内的随机整数的几个示例。示例 1:使用 Random().nextInt() 方法import 'dart:math';​randomGen(min, max) { // the nextInt method generate a non-ngegative random intege...


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

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。