【问题标题】:How to do random generator of elements of list?如何做列表元素的随机生成器?
【发布时间】:2020-12-22 02:59:16
【问题描述】:

我有清单:

    List quotes = [
        "Lmao this is text",
        "Okay okay go to next",
        "So, we are the champion nanana",
        "Gagagagaga",
        "What does the fox say?"
      ];

var _index = new Random();

我想从我的列表元素中创建随机文本生成器。 我在颤动中使用 statefull,当我点击按钮时,我想要列表中的新随机元素。 我的代码示例:

 children: [
                Text(quotes[_index]),
    
                Center(
                  child: Container(
                      child: FlatButton.icon(
                          onPressed: _showFate(),
                          icon: Icon(Icons.casino),
                          label: Text("New words!", style: TextStyle(
                            color: Colors.white
                          ),)),
_showFate() {
    setState(() {
      _index.nextInt(5);
    });

为什么它不起作用我不明白......

【问题讨论】:

    标签: flutter dart flutter-state


    【解决方案1】:

    _index 应该是 int 而不是 Random,您还应该在 setState 中将随机值重新分配给 _index

    看看这个。

    
    int _index = 0;
    
    _showFate(){
      setState(() {
       _index = Random().nextInt(5);
      });
    }
    

    【讨论】:

      【解决方案2】:

      只需在文本小部件中使用 _index.nextInt(quotes.length) 并调用 setState 进行更新:

      children: [
                      Text(quotes[_index.nextInt(quotes.length)]),
          
                      Center(
                        child: Container(
                            child: FlatButton.icon(
                                onPressed: _showFate(),
                                icon: Icon(Icons.casino),
                                label: Text("New words!", style: TextStyle(
                                  color: Colors.white
                                ),)),
      _showFate() {
          setState(() {});
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-09
        相关资源
        最近更新 更多