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.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With