【问题标题】:Add reward points flutter添加奖励积分flutter
【发布时间】:2020-06-30 21:49:23
【问题描述】:

我想做一个积分奖励应用,为此我使用了一个随机函数。

问题是我不知道如何将此号码添加到前一个号码中。获得总分。

这是我想在这里求和的结果。

修改后出现此错误

这是我的奖励应用的完整代码

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),
                        ),
                        ),
                      ],
                    ),
                  ), 
                ],
              ),
            ),
            ),
          ],
        ),
      ),
    ),
  ),
      
);
}
}

文件 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),
      );
    },
  )
);
}
}

文件 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)];
}
}

【问题讨论】:

    标签: flutter points


    【解决方案1】:

    你可以使用setState()函数来实现。

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

    如果您想在全球范围内存储总积分值,您应该查看shared preferences 包。

    能够在全局范围内使用该函数的最佳方法是将其包装在一个单独的全局类中。

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

    然后在你的其他类中你可以这样调用:

    ClassName.generateRandomNumber();
    

    您得到的错误是由于在 build() 函数之外调用 setState。像这样在构建函数中移动生成数字函数

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

    【讨论】:

    • 谢谢先生的帮助,我的问题是这个函数在另一个类上,我想在另一个类上调用它,我怎么能用你发给我的代码来做呢
    • 嘿@MrFlutter 你能用一个类样本更新你的问题吗
    • 我在两个文件 dart.谢谢你
    • @MrFlutter 是你在 github 上的代码吗?我想我需要看到更多的内容
    • 好的,发到这里
    猜你喜欢
    • 2012-07-29
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多