首页 > 解决方案 > 使用 FloatingButton (Flutter) 随机输出文本

问题描述

当我点击文本小部件上的 FloatingButton 时,需要从列表中输出一个随机项目。在网上尝试了很多方法,但似乎没有一个有效。

示例:我有 5 个任务: 吃三明治 打个盹 给你的朋友打电话 跑一公里 买些花。

现在,按一下按钮,我想显示一个任务,例如:

你的任务是……给你的朋友打电话。

还创建了一个包含项目列表的新 list.dart 文件。

第一次在这里发帖。任何帮助表示赞赏。谢谢!

标签: flutterflutter-dependencies

解决方案


使用随机数生成器获取介于 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;
    });
}


推荐阅读