Flutter 为什么在颤振中添加周期计时器后,每秒钟都要重新初始化一次?

Flutter 为什么在颤振中添加周期计时器后,每秒钟都要重新初始化一次?,flutter,dart,flutter-layout,dart-async,flutter-timer,Flutter,Dart,Flutter Layout,Dart Async,Flutter Timer,我正在尝试构建一个测验应用程序。当任何用户开始参加测验时,计时器就会启动,不知道为什么每秒钟都要重新初始化一次。布尔参数“已应答”每秒都被设置为false。因此,参与者可以多次回答同一个问题,从而导致错误的结果,并且假设不会发生。这里有一个片段- class MathQuizPlay extends StatefulWidget { final String quizId; MathQuizPlay({Key key, this.quizId}) : super(key: key);

我正在尝试构建一个测验应用程序。当任何用户开始参加测验时,计时器就会启动,不知道为什么每秒钟都要重新初始化一次。布尔参数“已应答”每秒都被设置为false。因此,参与者可以多次回答同一个问题,从而导致错误的结果,并且假设不会发生。这里有一个片段-

class MathQuizPlay extends StatefulWidget {
  final String quizId;
  MathQuizPlay({Key key, this.quizId}) : super(key: key);

  @override
  _MathQuizPlayState createState() => _MathQuizPlayState(this.quizId);
}

int total = 0;
int _correct = 0;
int _incorrect = 0;
int _notAttempted = 0;
int timer;
String showtimer;

class _MathQuizPlayState extends State<MathQuizPlay> {
  var quizId;
  _MathQuizPlayState(this.quizId);
  QuerySnapshot questionSnapshot;
  bool isLoading = true;

  getQuestionData(String quizId) async {
    return await Firestore.instance
        .collection('math')
        .document(quizId)
        .collection('QNA')
        .getDocuments();
  }

  @override
  void initState() {
    getQuestionData(quizId).then((value) {
      questionSnapshot = value;
      setState(() {
        total = questionSnapshot.documents.length;
        _correct = 0;
        _incorrect = 0;
        _notAttempted = questionSnapshot.documents.length;
        isLoading = false;
        timer = total * 15;
        showtimer = timer.toString();
      });
    });

    starttimer();
    super.initState();
  }

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

  Questions getQuestionModelFromDatasnapshot(
      DocumentSnapshot questionSnapshot) {
    final Questions questionModel = Questions(
        question: questionSnapshot.data['question'],
        option1: questionSnapshot.data['option1'],
        option2: questionSnapshot.data['option2'],
        option3: questionSnapshot.data['option3'],
        option4: questionSnapshot.data['option4'],
        correctOption: questionSnapshot.data['correctOption'],
        answered: false);

    return questionModel;
  }

  void starttimer() async {
    const onesec = Duration(seconds: 1);
    Timer.periodic(onesec, (Timer t) {
      setState(() {
        if (timer < 1) {
          t.cancel();
          Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                  builder: (context) => Result(
                        correct: _correct,
                        incorrect: _incorrect,
                        total: total,
                        notattempt: _notAttempted,
                        collection: 'math',
                        quizId: quizId,
                      )));
        } else {
          timer = timer - 1;
        }
        showtimer = timer.toString();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.teal[300],
        title: Text("Questions",
            style: TextStyle(
              color: Colors.white,
            )),
        elevation: 5.0,
        centerTitle: true,
      ),
      body: isLoading
          ? Container(
              child: Center(child: CircularProgressIndicator()),
            )
          : SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    height: 10,
                  ),
                  Center(
                      child: Container(
                          height: 60,
                          width: 60,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(36),
                            border: Border.all(
                              width: 2.0,
                              color: Colors.red.withOpacity(0.8),
                            ),
                          ),
                          child: Center(
                              child: Text(
                            showtimer,
                            style: TextStyle(
                                fontWeight: FontWeight.w500,
                                fontSize: 19.0,
                                color: Colors.red.withOpacity(0.8)),
                          )))),
                  SizedBox(
                    height: 10,
                  ),
                  Center(child: Text('Tap on the option to select answer')),
                  SizedBox(
                    height: 10,
                  ),
                  questionSnapshot.documents == null
                      ? Container(
                          child: Center(
                            child: Text("No Data"),
                          ),
                        )
                      : ListView.builder(
                          itemCount: questionSnapshot.documents.length,
                          shrinkWrap: true,
                          physics: ClampingScrollPhysics(),
                          itemBuilder: (context, index) {
                            return Padding(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 15.0, horizontal: 25),
                              child: QuizPlayTile(
                                questionModel: getQuestionModelFromDatasnapshot(
                                    questionSnapshot.documents[index]),
                                index: index,
                              ),
                            );
                          }),
                  SizedBox(
                    height: 30,
                  ),
                  Center(
                    child: RaisedButton(
                        padding:
                            EdgeInsets.symmetric(vertical: 18, horizontal: 60),
                        color: Colors.teal[300],
                        textColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(8.0)),
                        child: Text(
                          'Submit',
                          style: TextStyle(fontSize: 16),
                        ),
                        elevation: 7.0,
                        onPressed: () {
                          Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => Result(
                                        correct: _correct,
                                        incorrect: _incorrect,
                                        total: total,
                                        notattempt: _notAttempted,
                                        collection: 'math',
                                        quizId: quizId,
                                      )));
                        }),
                  ),
                  SizedBox(
                    height: 50,
                  )
                ],
              ),
            ),
    );
  }
}


类MathQuizPlay扩展了StatefulWidget{
最终字符串quizId;
MathQuizPlay({Key,this.quizId}):super(Key:Key);
@凌驾
_MathQuizPlayState createState()=>\u MathQuizPlayState(this.quizId);
}
int-total=0;
int _correct=0;
int _不正确=0;
int _notAttempted=0;
整数定时器;
字符串显示计时器;
类MathQuizPlayState扩展状态{
var quizId;
_MathQuizPlayState(这个叫quizId);
查询快照;
bool isLoading=true;
getQuestionData(字符串quizId)异步{
return wait Firestore.instance
.collection('数学')
.文件(quizId)
.collection('QNA')
.getDocuments();
}
@凌驾
void initState(){
getQuestionData(quizId)。然后((值){
问题=价值;
设置状态(){
总计=questionSnapshot.documents.length;
_正确=0;
_不正确=0;
_notAttempted=questionSnapshot.documents.length;
isLoading=false;
计时器=总数*15;
showtimer=timer.toString();
});
});
starttimer();
super.initState();
}
@凌驾
无效设置状态(fn){
如果(已安装){
超级设定状态(fn);
}
}
问题从DataSnapshot获取问题模型(
文档快照(快照){
最终问题模型=问题(
问题:questionSnapshot.data['question'],
选项1:questionSnapshot.data['option1'],
选项2:questionSnapshot.data['option2'],
选项3:questionSnapshot.data['option3'],
选项4:questionSnapshot.data['option4'],
correctOption:questionSnapshot.data['correctOption'],
回答:假);
回归模型;
}
void starttimer()异步{
const onesec=持续时间(秒:1);
定时器周期(1秒,(定时器t){
设置状态(){
如果(计时器<1){
t、 取消();
导航器。更换(
上下文
材料路线(
生成器:(上下文)=>结果(
正确:_正确,
不正确:\不正确,
总计:总计,
notattempt:_notattempt,
收藏:《数学》,
奎齐德:奎齐德,
)));
}否则{
定时器=定时器-1;
}
showtimer=timer.toString();
});
});
}
@凌驾
无效处置(){
super.dispose();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
背景颜色:Colors.teal[300],
标题:文本(“问题”,
样式:TextStyle(
颜色:颜色,白色,
)),
标高:5.0,
标题:对,
),
主体:卸载
?容器(
子对象:中心(子对象:CircularProgressIndicator()),
)
:SingleChildScrollView(
子:列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
大小盒子(
身高:10,
),
居中(
子:容器(
身高:60,
宽度:60,
装饰:盒子装饰(
边界半径:边界半径。圆形(36),
边界:边界(
宽度:2.0,
颜色:颜色。红色。不透明度(0.8),
),
),
儿童:中心(
子:文本(
showtimer,
样式:TextStyle(
fontWeight:fontWeight.w500,
字体大小:19.0,
颜色:颜色。红色。不透明度(0.8)),
)))),
大小盒子(
身高:10,
),
居中(子项:文本(“点击选项选择答案”),
大小盒子(
身高:10,
),
questionSnapshot.documents==null
?容器(
儿童:中心(
子项:文本(“无数据”),
),
)
:ListView.builder(
itemCount:questionSnapshot.documents.length,
收缩膜:对,
物理:ClampingScrollPhysics(),
itemBuilder:(上下文,索引){
返回填充(
填充:const EdgeInsets.symmetric(
垂直:15.0,水平:25),
孩子:QuizPlayTile(
questionModel:getQuestionModelFromDatasnapshot(
问题快照.文档[索引],
索引:索引,,
),
);
}),
大小盒子(
身高:30,
),
居中(
孩子:升起按钮(
衬垫:
边缘组。对称(垂直:18,水平)
import 'package:circular_countdown_timer/circular_countdown_timer.dart';

class PhyQuizPlay extends StatefulWidget {
  final String quizId;
  PhyQuizPlay({Key key, this.quizId}) : super(key: key);

  @override
  _PhyQuizPlayState createState() => _PhyQuizPlayState(this.quizId);
}

int total = 0;
int _correct = 0;
int _incorrect = 0;
int _notAttempted = 0;
int timer;

class _PhyQuizPlayState extends State<PhyQuizPlay> {
  var quizId;
  _PhyQuizPlayState(this.quizId);
  QuerySnapshot questionSnapshot;
  bool isLoading = true;

  getQuestionData(String quizId) async {
    return await Firestore.instance
        .collection('physics')
        .document(quizId)
        .collection('QNA')
        .getDocuments();
  }

  @override
  void initState() {
    getQuestionData(quizId).then((value) {
      questionSnapshot = value;
      setState(() {
        total = questionSnapshot.documents.length;
        _correct = 0;
        _incorrect = 0;
        _notAttempted = total;
        isLoading = false;
        timer = total * 15;
      });
    });
    super.initState();
  }

  Questions getQuestionModelFromDatasnapshot(
      DocumentSnapshot questionSnapshot) {
    final Questions questionModel = Questions(
        question: questionSnapshot.data['question'],
        option1: questionSnapshot.data['option1'],
        option2: questionSnapshot.data['option2'],
        option3: questionSnapshot.data['option3'],
        option4: questionSnapshot.data['option4'],
        correctOption: questionSnapshot.data['correctOption'],
        answered: false);

    return questionModel;
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.teal[300],
        title: Text("Questions",
            style: TextStyle(
              color: Colors.white,
            )),
        elevation: 5.0,
        centerTitle: true,
      ),
      body: isLoading
          ? Container(
              child: Center(child: CircularProgressIndicator()),
            )
          : SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(
                    height: 10,
                  ),
                  Center(
                      child: CircularCountDownTimer(
                    width: 80,
                    height: 80,
                    duration: timer,
                    fillColor: Colors.red,
                    color: Colors.white38,
                    isReverse: true,
                    onComplete: () {
                      Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                              builder: (context) => Result(
                                    correct: _correct,
                                    incorrect: _incorrect,
                                    total: total,
                                    notattempt: _notAttempted,
                                    collection: 'physics',
                                    quizId: quizId,
                                  )));
                    },
                  )),
                  SizedBox(
                    height: 10,
                  ),
                  Center(child: Text('Tap on the option to select answer')),
                  SizedBox(
                    height: 10,
                  ),
                  questionSnapshot.documents == null
                      ? Center(
                          child: CircularProgressIndicator(),
                        )
                      : ListView.builder(
                          itemCount: questionSnapshot.documents.length,
                          shrinkWrap: true,
                          physics: ClampingScrollPhysics(),
                          itemBuilder: (context, index) {
                            return Padding(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 15.0, horizontal: 25),
                              child: QuizPlayTile(
                                questionModel: getQuestionModelFromDatasnapshot(
                                    questionSnapshot.documents[index]),
                                index: index,
                              ),
                            );
                          }),
                  SizedBox(
                    height: 30,
                  ),
                  Center(
                    child: RaisedButton(
                        padding:
                            EdgeInsets.symmetric(vertical: 18, horizontal: 60),
                        color: Colors.teal[300],
                        textColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius: new BorderRadius.circular(8.0)),
                        child: Text(
                          'Submit',
                          style: TextStyle(fontSize: 16),
                        ),
                        elevation: 7.0,
                        onPressed: () {
                          Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => Result(
                                        correct: _correct,
                                        incorrect: _incorrect,
                                        total: total,
                                        notattempt: _notAttempted,
                                        collection: 'physics',
                                        quizId: quizId,
                                      )));
                        }),
                  ),
                  SizedBox(
                    height: 50,
                  )
                ],
              ),
            ),
    );
  }
}