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?
You can choose an alternative, by using the dart:math
library and generating the random number from the index.
import 'dart:math';
import 'package:flutter/material.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
_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"
];
return Scaffold(
appBar: AppBar(
title: const Text("GeeksForGeeks"),
backgroundColor: Colors.green,
),
body: Container(
child: Center(
child: ElevatedButton(
onPressed: () {
final _random = new Random();
var country = countries[_random.nextInt(countries.length)];
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 general way to generate random
element from a list.
import "dart:math";
var list = ['a','b','c','d','e'];
final _random = new Random();
var element = list[_random.nextInt(list.length)];