How to do random generator of elements of list?

Issue

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…

Solution

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

Answered By – Josteve

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *