Calulate two random numbers in flutter

5,463

The error is telling you that you're trying to add two Random objects, and not two numbers. You're printing them correctly, using nextInt() on your loops, but when you try to sum them, you're using the original variable of the type Random.

Try this:

class _MyHomeState extends State<MyHome> {
  @override
  Widget build(BuildContext context) {

    // Instantiate a Random class object
    var numGenerator = new Random();

    //You don't need a second loop because it was the same exact code,
    //only with a different variable name.
    for (var i = 0; i < 10; i++) {
      print(numGenerator.nextInt(10));
    }
    // Save the numbers you generated. Each call to nextInt returns a new one
    var num1 = numGenerator.nextInt(10);
    var num2 = numGenerator.nextInt(10);
    var sum = num1 + num2;

    //use num1, num2 and sum as you like    

    return Container();
  }
}
Share:
5,463
J.W
Author by

J.W

I don't have very much experience of coding, but now I'm trying to learn flutter with the aim of being able to make some simple apps.

Updated on December 09, 2022

Comments

  • J.W
    J.W over 1 year

    I'm trying to generate two different random numbers and add those together, but Flutter doesn't seem to like my math. I keep getting the message that '+' isn't defined for the class Random.

    import 'package:flutter/material.dart';
    import 'dart:math';
    
    void main() => runApp(MaterialApp(
          title: 'Random Numbers',
          theme: ThemeData(primarySwatch: Colors.orange),
          home: MyHome(),
        ));
    
    class MyHome extends StatefulWidget {
      @override
      _MyHomeState createState() => _MyHomeState();
    }
    
    class _MyHomeState extends State<MyHome> {
      @override
      Widget build(BuildContext context) {
        var num1 = new Random();
        for (var i = 0; i < 10; i++) {
          print(num1.nextInt(10));
        }
        var num2 = new Random();
        for (var i = 0; i < 10; i++) {
          print(num2.nextInt(10));
        }
        //var sum = num1 + num2;
    
        return Container();
      }
    }
    

    My goal is to display it something like this: "2 + 5 = " where the user will fill in the answer. If correct do this else do that.