I want to make a reward points app, for that i use a random function.

The problem is i don't know how to add this number to the previous number. to get sum points. enter image description here

And here is the result i want to have the sum point here . enter image description here

After modification i get this error

enter image description here

here is the complete code for my reward app

rewards.dart

import 'dart:async';
import 'package:fid786/Services/CardScreen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fid786/styles.dart';
import 'package:fid786/Services/ClasNumber.dart';
class RewardsScreen extends StatefulWidget {
@override
_RewardsScreenState createState() => _RewardsScreenState();
}
class _RewardsScreenState extends State<RewardsScreen> {
@override
void initState() {
super.initState();
startTimer();
}
startTimer() async{
  var duration=Duration(seconds: 4);
  return Timer(duration,route);
}
route(){
  Navigator.pushReplacement(context, MaterialPageRoute(builder: 
(context)=>CardScreen()));
}                       
@override
Widget build(BuildContext context) {
return Scaffold(
  resizeToAvoidBottomPadding: false,
  body: AnnotatedRegion<SystemUiOverlayStyle>(
    value: SystemUiOverlayStyle.light,
    child: Container(
    height: MediaQuery.of(context).size.height,
    width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: [0.1, 0.4, 0.7, 0.9],
          colors: [
            Color(0xFF3594DD),
            Color(0xFF4563DB),
            Color(0xFF5036D5),
            Color(0xFF5B16D0),
          ],
        ),
      ),
      child: Padding(
        padding: EdgeInsets.only(top:80),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
             Expanded(
                    flex: 8,
            child:Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width,
              //height: 600.0,
              child: PageView(
                children: <Widget>[

                    Padding(
                     padding: EdgeInsets.symmetric(horizontal: 2),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Center(
                          child: ClipRRect(
                          borderRadius: BorderRadius.circular(50.0),
                          child: Image(
                            image: AssetImage(
                              'assets/images/congrats.gif',
                            ),
                            height: 300.0,
                            width: 300.0,
                            fit: BoxFit.fill,
                          ),
                          ),
                        ),
                        SizedBox(height: 30.0),
                        Text(
                          ' Congratulations, You have Got',
                           style: kTitleStyle,
                        ),
                        SizedBox(height: 20.0),
                        Center(
                        child:Text(
                          ClassName.generateRandomNumber().toString(),   
                          style: TextStyle(color: Colors.greenAccent,
                          fontWeight: FontWeight.bold,
                          fontSize: 50)),
                      ),
                     SizedBox(height: 10.0),

                        Center(
                        child:Text(
                          '  Points ',
                          style: kTitleStyle,
                        ),
                        ),
                         SizedBox(height: 50.0),

                        Center(
                        child:Text(
                          'Earn More Points and Win Prizes ',
                          style:
                          TextStyle(
                          color: Colors.yellowAccent,
                          fontWeight: FontWeight.bold,
                          fontSize: 16,
                          fontFamily: 'muso',
                          decoration: TextDecoration.underline),
                        ),
                        ),
                      ],
                    ),
                  ), 
                ],
              ),
            ),
            ),
          ],
        ),
      ),
    ),
  ),

);
}
}

file CardScreen.dart

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:fid786/ScanQR/Card_Scanner.dart';
import 'package:fid786/Authentification/LogInScreen.dart';
import 'package:fid786/Services/ClasNumber.dart';
class CardScreen extends StatefulWidget {
@override
_CardScreenState createState()=>_CardScreenState();

}
class _CardScreenState extends State<CardScreen>{
FirebaseAuth auth=FirebaseAuth.instance;
Future<void>logOut() async{
FirebaseUser user=auth.signOut() as FirebaseUser; 
return user; 
}
@override
void initState() {
super.initState();
}
int points = 0;
int generateNumber() {

                      int newPoints = ClassName.generateRandomNumber();
setState(() {
points += newPoints;
});
return points;
                        }
@override
Widget build(BuildContext context){

return Scaffold(
  backgroundColor:Color(0xffffffff),
  appBar:AppBar(
    backgroundColor: Colors.greenAccent,
    title:Text("Loyalty Points"),
    actions: <Widget>[
      SizedBox(width:1.0),
      FlatButton.icon(onPressed: (){
        logOut();
        Navigator.pushReplacement(context, MaterialPageRoute(builder: 
   (BuildContext context)=>LogInScreen()));
      },
      icon: Icon(Icons.shopping_cart,size: 40.0,color: 
   Colors.pinkAccent,), label: Text("Log Out",style: TextStyle(color: 
   Colors.pinkAccent),))
   ],
   ),
    body: StreamBuilder(
      stream:Firestore.instance.collection('screen').snapshots(),
      builder:(context,snapshot){
          if(!snapshot.hasData) return Text('');

    return Column(
    children: <Widget>[
        Padding(

                    padding: EdgeInsets.only(left: 8.0, right: 8.0,top: 
    40.0),
                    child: Container(
                      width: MediaQuery.of(context).size.width,
                      height: 80.0,
                      child: Padding(
                        padding: EdgeInsets.only(top: 8.0, bottom: 8.0),
                        child: Material(
                          shape: Border.all(width: 2.0, color: 
    Colors.blueAccent),
                          color: Colors.white,
                          elevation: 18.0,
                          shadowColor: Color(0x802196F3),

                          child: Center(
                            child: Padding(
                              padding: EdgeInsets.all(5.0),
                              child: Row(
                               // mainAxisAlignment:
                                 //   MainAxisAlignment.spaceBetween,
                                children: <Widget>[       
                                  Text(
                                    snapshot.data.documents[0]['player'],
                                    style: TextStyle(
                                        color: Colors.greenAccent,
                                        fontWeight: FontWeight.bold,
                                        fontSize: 18.0),
                                  ),        
                                // mainAxisAlignment:
                                 //   MainAxisAlignment.spaceBetween,
                                 SizedBox(width:175),
                                  Column(

                                    mainAxisAlignment:
                                        MainAxisAlignment.center,
                                    children: <Widget>[

                        Text(
                          generateNumber().toString(),
                          style: TextStyle(color: Colors.greenAccent,
                          fontWeight: FontWeight.bold,
                          fontSize: 25)),

                                      Text(
                                        'Points',
                                        style: TextStyle(
                                            color: Colors.pinkAccent,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 16.0,
                                            fontFamily: 'muso'),
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
        ),

    ],
  );
      }
    ), 
        floatingActionButton: FloatingActionButton(
    backgroundColor: Color(0xFFFA7397),
    child: Icon(
      FontAwesomeIcons.listUl,
      color: Color(0xFFFDDE42),
    ),
    onPressed: () {
      Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => HomePage(), fullscreenDialog: true),
      );
    },
  )
);
}
}

file ClasNumber.dart

import 'dart:math';

class ClassName{

static int generateRandomNumber() {
List<int> pointValue = [5,6,7,8,10,15];
return pointValue[new Random().nextInt(pointValue.length)];
}
}


Solution 1: ByteMe

you can use setState() function to achieve this.

int points = 0;
int newPoints = generateRandomNumber();
setState(() {
  points += newPoints
});

If you would like to store the total points value globally, you should look into the shared preferences package.

The best way to be able to use the function globally is to wrap it in a separate global class.

class ClassName{
  static int generateRandomNumber() {
    return pointValue[new Random().nextInt(pointValue.length)];
  }
}

And then in your other classes you could call like this:

ClassName.generateRandomNumber();

The error you got was due to calling setState outside of the build() function. Move the generate number function inside the build function like this

@override
Widget build(BuildContext context){
int generateNumber() {
 int newPoints = ClassName.generateRandomNumber();
 setState(() {
   points += newPoints;
 });
 return points;
}