skip to Main Content

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


  1. You are recreating new variable, remove the int

     void randomNumberFunction() {
        setState(() {
          Random random = Random();
          randomNumber = random.nextInt(10);
          print(randomNumber);
        });
      }
    

    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.

    Login or Signup to reply.
  2. 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:

    import 'dart:math';
    import 'package:flutter/material.dart';
    
    class RandomNum extends StatefulWidget {
      const RandomNum({super.key});
    
      @override
      State<RandomNum> createState() => _RandomNumState();
    }
    
    class _RandomNumState extends State<RandomNum> {
      Random random = Random();
      int randomNumber = 0;
    
      void randomNumberFunction() {
        setState(() {
          randomNumber = random.nextInt(10);
          print(randomNumber);
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Column(
            children: [
              Text('$randomNumber'),
              ElevatedButton(onPressed: randomNumberFunction, child: Text('Guess'))
            ],
          ),
        );
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search