2

I have list:

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

And I want to create random text generator from my elements of list. I use statefull in flutter and when I tap the button, I want new random element from my list. Example of my code:

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

Why it does not work I do not understand...

influtter
  • 23
  • 1
  • 4

2 Answers2

2

_index should be an int not Random and you should also reassign the random value to _index in the setState

Check this out.


int _index = 0;

_showFate(){
  setState(() {
   _index = Random().nextInt(5);
  });
}
Josteve
  • 11,459
  • 1
  • 23
  • 35
0

Just use _index.nextInt(quotes.length) inside your text widget and call setState to update:

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(() {});
}
MindStudio
  • 706
  • 1
  • 4
  • 13