Reputation: 43
I want to display a number from a list randomly as soon as I open the page without needing to click the number to change. Tried checking online, but had no luck finding any working solutions.
Update 1: It doesn't necessarily have to be a number. Also, below is my code so far. Only when I click the text changes. I'm still not able to have it dynamically show different "randomQuote" every time I open the page in the app
Update 2: Figured it out :)
static List randomQuote = ['a', 'b', 'c', 'd','f'];
Random random = new Random();
var shuffleList = randomQuote.toList()..shuffle();
int index = 0;
void changeIndex() {
setState(() => index = Random().nextInt(shuffleList.length));
}
@override
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
Padding(
padding:
const EdgeInsets.only(bottom: 5, top: 5, left: 20, right: 20),
child: Text(
shuffleList[index].toString(),
style: TextStyle(
color: Colors.black87,
fontFamily: 'Roboto-boldItalics',
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}
}
Upvotes: 0
Views: 2698
Reputation: 119
You can try shuffle(), which is provide with the Lists in flutter. example :
listObjects.shuffle();
Upvotes: -1
Reputation: 1619
Do this in the initState
function:
var myList= [1,2,3,4,5];
myList.shuffle();
// Display `myList.first`
Upvotes: 2
Reputation: 1397
You can define your randomized function in your init state
i.e.
void initState(){ int randomNumber=Random().nextInt(yourList.length) }
then you can use randomNumber whatever you want.
Upvotes: 1