首页 > 解决方案 > 如何一次访问一个按钮?

问题描述

我解决了当前有关锁定和解锁按钮的问题。我的等级基于用户获得的分数。如果他们得到25分及以上的分数,他们将进入下一个级别。

现在这里的问题是,由于我的测验是与不同的 JSON 文件共享一个代码,当用户在第一阶段完善分数时,整个关卡将解锁,这是一个禁忌。这个想法是即使他们得分完美,下一阶段也不会解锁整个关卡。我试着想办法做到这一点,但我什么也没想到。

这是我的测验页面:

import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:baybay_app/Quiz/NextLevel class.dart';
import 'package:baybay_app/Quiz/QuizHome.dart';
import 'package:baybay_app/Quiz/ResultPage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class Quizjson extends StatelessWidget {
  String roundName;
  bool isComplete = false;
  Quizjson(this.roundName, mark);
  String assettoload;
  int question;


  // a function
  // sets the asset to a particular JSON file
  // and opens the JSON
  setasset() {
    if (roundName == 'Easy Round') {
      assettoload ='assets/Sample.json';
    } else if (roundName == 'Average Round') {
       assettoload = 'assets/Medium.json';

    } else if (roundName == 'Hard Round') {
      assettoload = 'assets/Hard.json';
    }else {
      assettoload = 'assets/Intermediate.json';
    }




  }
  @override
  Widget build(BuildContext context) {

    setasset();
    return FutureBuilder(
        future: DefaultAssetBundle.of(context).loadString(assettoload, cache: false),
        builder: (context, snapshot){
          List mydata = json.decode(snapshot.data.toString());
          if(mydata == null){
            return Scaffold(
              body: Center(
                child: Text(
                  "Loading",
                ),
              ),
            );
          }else{
            return quizpage(mydata: mydata);
          }

        }
    );
  }
}


class quizpage extends StatefulWidget {
  String langname;
  var mydata;
  quizpage({Key key, @required this.mydata}): super(key: key);

  @override
  _quizpageState createState() => _quizpageState(mydata);
}

class _quizpageState extends State<quizpage> {
  var mydata;
  _quizpageState(this.mydata);
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    return Scaffold(
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Expanded(
            flex: 3,
            child: Container(
            padding: EdgeInsets.all(20.0),
              alignment: Alignment.bottomLeft,
              child: Text(mydata[0][question.toString()])
            ),
          ),
          Expanded(
            flex: 6,
            child: Container(
            child: Column(
              children: [
                Row(
                  children:[
                    ChoiceButton("a"),
                    ChoiceButton("b")
                  ]
                ),
                Row(
                  children:  [
                    ChoiceButton("c"),
                    ChoiceButton("d"),
                  ]
                )
              ]
            ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Container(
                  alignment: Alignment.topCenter,
            child: Center(
              child: Text(
               showtimer,
                style:  TextStyle(
                  fontSize: 20.0
                ),
              ),
            ),
            ),
          ),
        ],
      )
    );
  }






Widget ChoiceButton(String k) {
    return Padding(
      padding: EdgeInsets.symmetric(
          vertical: 10.0,
          horizontal: 10.0),
        child: MaterialButton(
          onPressed: ()=>CheckAnswer(k),
          child: Text(
          mydata[1][question.toString()][k],
          style: TextStyle(
              color: Colors.white
          )),
          color: btncolor[k],
        ),
    );

}
  Color colorsToShow = Colors.brown[700];
  Color right = Colors.greenAccent[700];
  Color wrong = Colors.redAccent[700];
  int mark = 0;
  int question = 1;
  int timer = 30;
  String showtimer = "30";
  bool canceltimer = false;
  bool isComplete = false;

  Map<String,Color> btncolor = {
    "a" : Colors.brown[700],
    "b" : Colors.brown[700],
    "c" : Colors.brown[700],
    "d" : Colors.brown[700],
   };

  @override
  void initState(){
    starttimer();
    super.initState();
  }

  @override
  void setState(fn){
    if(mounted){
      super.setState(fn);
    }
  }

  void starttimer() async {
    const onesec = Duration(seconds: 1);
    Timer.periodic(onesec, (Timer t){
      setState(() {
        if(timer < 1){
          t.cancel();
          NextQuestion();
        }
        else if(canceltimer==true){
            t.cancel();
        }
        else{
          timer = timer - 1;
        }
        showtimer = timer.toString();
      });
    });

  }

  void NextQuestion(){
    canceltimer = false;
    timer = 30;
    setState(() {
      if(question< 10){
        question++;
      }
      else{
        Navigator.of(context).pushReplacement(MaterialPageRoute(
          builder: (context) => ResultPage(mark: mark),

        ));}
      btncolor["a"] = Colors.brown[700];
      btncolor["b"] = Colors.brown[700];
      btncolor["c"] = Colors.brown[700];
      btncolor["d"] = Colors.brown[700];
      isComplete = true;
    });
    starttimer();
}

  void CheckAnswer(String k) {
    if(mydata[2][question.toString()] == mydata[1][question.toString()][k]){
      mark = mark+5;
      colorsToShow = right;
    }

    else{
      colorsToShow = wrong;
    }
    setState(() {
      btncolor[k] = colorsToShow;
    });

    Timer(Duration(seconds: 2), NextQuestion);
  }

}

这是我的测验主页:

import 'package:baybay_app/Quiz/QuizTracingSound.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:baybay_app/Quiz/QuizTracingSound.dart';

class QuizHome extends StatefulWidget {
  int mark = 0;
  QuizHome({ @required this.mark });
  @override
  _QuizHomeState createState() => _QuizHomeState(mark);
}

class _QuizHomeState extends State<QuizHome> {

createAlertDialouge(BuildContext context){
  return showDialog(context: context, builder: (context){
    return AlertDialog(
      title: Text('Not Complete'),
      content: Text('Please score 25 above mark'),
      actions: [
        Center(
          child: RaisedButton(
            onPressed: (){Navigator.of(context).pop();},
            color: Colors.grey[100],
          ),
        ),

      ],
      shape: RoundedRectangleBorder(side: BorderSide(width: 16.0, color: Colors.red.shade100)),
      backgroundColor: Colors.lightBlue.shade100,
    );
  });
}

createAlertDialougeOne(BuildContext context){
  return showDialog(context: context, builder: (context){
    return AlertDialog(
      title: Text('Not Complete'),
      content: Text('Please score 35 and above mark'),
      actions: [
        Center(
          child: RaisedButton(
            onPressed: (){Navigator.of(context).pop();},
            color: Colors.grey[100],
          ),
        ),

      ],
      shape: RoundedRectangleBorder(side: BorderSide(width: 16.0, color: Colors.red.shade100)),
      backgroundColor: Colors.lightBlue.shade100,
    );
  });
}

createAlertDialougeTwo(BuildContext context){
  return showDialog(context: context, builder: (context){
    return AlertDialog(
      title: Text('Not Complete'),
      content: Text('Please score 35 and above mark'),
      actions: [
        Center(
          child: RaisedButton(
            onPressed: (){Navigator.of(context).pop();},
            color: Colors.grey[100],
          ),
        ),

      ],
      shape: RoundedRectangleBorder(side: BorderSide(width: 16.0, color: Colors.red.shade100)),
      backgroundColor: Colors.lightBlue.shade100,
    );
  });
}

  int mark = 0 ;
  _QuizHomeState(this.mark);
  String langname;
  bool isComplete = false;
@override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    List <String> images = [
      'assets/Ba.gif',
      'assets/GA.PNG',
      'assets/HA.PNG',
      'assets/SA.PNG'
    ];



    return Scaffold(
      appBar: AppBar(
        title: Text('Quiz Home '),
      ),
      body:ListView(
           children: <Widget>[
         FlatButton(
           child: CustomCard('Easy Round', images[0], des[1], isComplete, Colors.green, mark),

             onPressed: () {
               { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson("Easy Round", mark = 5),
               ));}
             }

          ),
      SizedBox(
        height: 20.0,
      ),
      FlatButton(
          child: CustomCard('Average Round', images[1], des[1], isComplete, lockOrNot, mark),
         onPressed: _onPressedOne,
      ),
      SizedBox(
        height: 20.0,
      ),
      FlatButton(
        onPressed: _onPressedTwo,
          child: CustomCard('Hard Round', images[2],des[2], isComplete, btncolor, mark)
      ),
      SizedBox(
        height: 20.0,
      ),
      FlatButton(
        onPressed: _onPressedThree,
          child: CustomCard('Intermediate Round', images[3],des[3], isComplete, btncolor, mark )
      ),

           ],
      )

    );
  }
  List <String> des = [
    "The easy round lets you test your knowledge in determining letters. Are you up for the challenge? Click here!!!",
    "Do you want to step up your baybayin game? Let's see if you can distinguish words! Click here!!!",
    "Do you know how to construct sentences with the use of Baybayin? Click here!!!",
    "Masters of baybayin can only enter this quiz! Are you one of them? Click Here!!!",

  ];

Color btncolor;
 Widget CustomCard(String roundName,images,String des, bool isComplete, Color btncolor, int mark ) {




    return Material(
               color: btncolor,
              elevation: 10.0,
              borderRadius: BorderRadius.circular(20.0),
              child: Container(
                child: Column(
                 children: <Widget>[
                   Text(
                    '$mark'
                   ),
                   Padding(
                     padding: EdgeInsets.symmetric(
                       vertical: 10.0,
                     ),
                     child: Material(
                       elevation: 5.0,
                       borderRadius: BorderRadius.circular(100.0),
                       child: Container(
                         height: 200.0,
                         width: 200.0,
                         child:ClipOval(
                           child: Image(
                             image: AssetImage(images),
                           ),
                         )
                       ),
                     ),

                   ),
                   Center(
                     child: Text( roundName,
                     style: TextStyle(
                       color: Colors.white,
                       fontSize: 20.0,
                       letterSpacing: 10.0,
                       fontFamily: 'S'
                     ),),
                   ),
                   Container(

                     padding:EdgeInsets.all(8.0),
                     child: Text(
                       des,
                       style: TextStyle(
                         color: Colors.white,
                         letterSpacing: 1.0
                       ),
                     ),
                   ),
                 ],
                ),
              ),
            );

 }
 Color unlockColor = Colors.green;
 Color lockColor = Colors.grey;
Color lockOrNot = Colors.grey;



void _onPressedOne() {
  int marks1 = 24;
    if(marks1< mark){
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson( "Average Round", 7 ),
      ));

    }
    else{

      createAlertDialouge(context);
    }
}
  void _onPressedTwo() {
    int marks2 = 34;
    int marc = mark;

    if( marks2 < marc ){
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson("Hard Round", 7 ),

      ));

    }
    else{
      createAlertDialougeOne(context);
    }
  }

  void _onPressedThree() {
    int marks3 = 49;
    int marc = mark;

    if( marks3 < marc ){
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> Quizjson("Average Round", 8),

      ));
    }
    else{
      createAlertDialougeTwo(context);
    }
  }

}

如果您需要结果页面:

import 'package:baybay_app/Quiz/QuizHome.dart';
import 'package:flutter/material.dart';

class ResultPage extends StatefulWidget {
  int mark;
  ResultPage({Key key, @required this.mark}) : super(key: key);
  @override
  _ResultPageState createState() => _ResultPageState(mark);
}

class _ResultPageState extends State<ResultPage> {
  List<String> images = [
    'assets/excellent.jpg',
    'assets/good.png',
    'assets/Sorry.png'
  ];
  String message;
  String image;
  @override
  void initState(){
    if(mark<5){
      image = images[2];
      message = 'Try Again..\n' + 'You scored $mark';
    }
    else if(mark==5){
      image = images[1];
      message = 'Good.. \n' + 'You scored $mark';
    }
    else{
      image = images[0];
      message =  'Excellent!!!...\n' + 'You scored $mark';
    }
  }
  int mark;
  _ResultPageState(this.mark);
  @override
  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(
        title: Text(
          "Result"
        )
      ),
      body: Column(
        children:[
          Expanded(
            flex: 6,
            child: Material(
              elevation: 5.0,
              child: Container(
                child:Column(
                  children: [
                    Material(
                      child: Container(
                        width: 300.0,
                        height: 300.0,
                        child: ClipRect(
                          child: Image(
                            image: AssetImage(
                              image,
                            )
                          )
                        ),
                      ),
                    ),
                    Center(
                      child: Text(
                        message,
                        style: TextStyle(
                          fontSize: 20.0,
                          fontFamily: 'Staatliches'
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
          ),
          Expanded(
            flex:4,
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
              children:<Widget>[
               OutlineButton(
                  onPressed: () {
                     Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context)=> QuizHome(mark:mark)));
                  },
                  child: Text(
                    'Continue',

                    style: TextStyle(
                      fontSize: 20.0,
                      fontFamily: 'Staatliches'
                    )
                  ),
                   padding: EdgeInsets.symmetric(vertical: 10.0,horizontal: 15.0),
                 borderSide: BorderSide(width: 3.0,color: Colors.brown[700])
                )
              ],
            )

          )
        ]
      )
    );
  }
}

接下来我可以尝试什么?

标签: androidflutterdart

解决方案


推荐阅读