I am trying to create random numbers after clicking the button. it works in the console but not on the UI. Need help with this. I am missing something
import 'dart:math';
import 'package:flutter/material.dart';
class RandomNum extends StatefulWidget {
const RandomNum({super.key});
@override
State<RandomNum> createState() => _RandomNumState();
}
Random random = Random();
int randomNumber = random.nextInt(10);
class _RandomNumState extends State<RandomNum> {
void randomNumberFunction() {
setState(() {
Random random = Random();
int randomNumber = random.nextInt(10);
print(randomNumber);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
children: [
Text(randomNumber.toString()),
ElevatedButton(onPressed: randomNumberFunction, child: Text('Guess'))
],
),
);
}
}
2
Answers
You are recreating new variable, remove the
int
also you can use initState to set initial number instead of global and use the same
random
instance to generate number inside the function rest of the time.You have globally initialize the variables and then again in your
setState
method, remove those and define it within the class.Here’s your updated code: