2

我有清单:

    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);
    });

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

4

2 回答 2

2

_index应该int不是Random,您还应该将随机值重新分配_indexsetState

看一下这个。


int _index = 0;

_showFate(){
  setState(() {
   _index = Random().nextInt(5);
  });
}
于 2020-09-02T21:56:50.603 回答
0

只需_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(() {});
}
于 2020-09-02T22:06:23.560 回答