flutter - 使用 FloatingButton (Flutter) 随机输出文本
问题描述
当我点击文本小部件上的 FloatingButton 时,需要从列表中输出一个随机项目。在网上尝试了很多方法,但似乎没有一个有效。
示例:我有 5 个任务: 吃三明治 打个盹 给你的朋友打电话 跑一公里 买些花。
现在,按一下按钮,我想显示一个任务,例如:
你的任务是……给你的朋友打电话。
还创建了一个包含项目列表的新 list.dart 文件。
第一次在这里发帖。任何帮助表示赞赏。谢谢!
解决方案
使用随机数生成器获取介于 0 和列表长度之间的随机数。
import 'dart:math';
...
final listItem = ["item1", "item2", "item3"]; /// the list which has tasks
final String randomString = ''; /// initially defined as empty
...
Text(randomString), /// example widget where task is to be displayed
...
onTap: () {
// function called when there's a tap on the FloatingButton
Random random = new Random();
int randomIndex = random.nextInt(listItems.length); // where listItems is the list in list.dart file
final randomItem = listItems[randomIndex]; /// random item required
setstate((){
randomString = randomItem;
});
}
推荐阅读
- r - 是否有任何 r 函数可以在 R 中将列标题(例如:2018 年 1 月、2018 年 2 月等)“2018 年 1 月”转换为“1 月 18 日”?
- ruby-on-rails - 如何查询具有属性对数组的记录?
- c++11 - 修复警告“Wundefined-var-template”
- python - Python 请求将文件名而不是内容写入网页
- android - Expo.Pedometer.getStepCountAsync 的奇怪属性
- sql - BigQuery 相当于 SQL 查询
- sql - sql:如何删除某些列的所有行?
- airflow - Airflow 无法从 initdb 上的自定义数据模型创建表
- mysql - 如何将触发器从一个表复制到另一个表
- nginx - .php 文件被下载而不是显示