I would like to display a random string when i click the ElevatedButton.However,the same string still display when i click ElevatedButton. The string will be randomly change only when i restart the app.
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
// ignore: library_private_types_in_public_api
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
// Random List Here
List<String> countries = [
"USA",
"United Kingdom",
"China",
"Russia",
"Brazil"
];
countries.shuffle();
String country = countries[0];
return Scaffold(
appBar: AppBar(
title: const Text("GeeksForGeeks"),
backgroundColor: Colors.green,
),
// ignore: avoid_unnecessary_containers
body: Container(
child: Center(
child: ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text("Shuffle List in Flutter"),
content: Text(country),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(ctx).pop();
},
child: Container(
color: Colors.green,
padding: const EdgeInsets.all(14),
child: const Text("okay"),
),
),
],
),
);
},
child: const Text("Show alert Dialog box"),
),
),
),
);
}
}
The same countries name will be displat everytime i click the button
Restart the app is the only way i can randomly change the country name.
what i need to add on in order to display random country everytime i click the button?
2
Answers
You can choose an alternative, by using the
dart:math
library and generating the random number from the index.The general way to
generate random
element from a list.You can use
Random().nextInt(max)
to get a random index of the list instead ofshuffle
.I hope this helps.