【问题标题】:how to set highscore for quiz/game in flutter?如何在颤动中为测验/游戏设置高分?
【发布时间】:2018-11-01 15:34:40
【问题描述】:

我们第一次打开设置高分为0,在颤振中 它将检查分数并更新其值。 我也使用了共享首选项,它不起作用。

import './question.dart';
import 'package:shared_preferences/shared_preferences.dart';

 class Quiz { 
 List<Question> _questions;
int _currentQuestionIndex = -1;
int _score = 0;
int _highscore;

  Future checkFirstSeen() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
    bool _seen = (prefs.getBool('seen') ?? false);

   if (_seen) {
  _highscore=_highscore;
   } else {
  prefs.setBool('seen', true);
  _highscore=0;
    }
}

 Quiz(this._questions) {
    _questions.shuffle();
  }

   List<Question> get questions => _questions;
  int get length => _questions.length;
  int get questionNumber => _currentQuestionIndex+1;
  int get score => _score;
  int get highscore => _highscore;

 Question get nextQuestion {
  _currentQuestionIndex++;
  if (_currentQuestionIndex >= length) return null;
  return _questions[_currentQuestionIndex];
  }

 void answer(bool isCorrect) {
  if (isCorrect) _score++;
 }

 //added fun for highscore
 void check() {  
 if (_score > _highscore) {
    _highscore = _score;
 } else {
  _highscore = _highscore;
 }
 }

 }

这返回我总是得分和高分相同的值(数字)。告诉我解决方案

【问题讨论】:

  • _highscore 没有初始化,所以如果你在第一次安装后重新运行你的应用程序,它是空的。
  • 是的,当我运行应用程序时,它显示高分和分数相同。
  • @PrakashKing 如果它确实解决了您的问题,请接受答案。

标签: android flutter google-play-games flutter-dependencies


【解决方案1】:

如果我正确理解您要执行的操作,您需要编辑 Quiz.checkFirstSeen()Quiz.check() 方法,如下所示:

Future<void> checkFirstSeen() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  _highscore = prefs.getInt('highScore') ?? 0;
}

Future<void> check() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  if (_score > _highscore) {
    _highscore = _score;
    await prefs.setInt('highScore', _highscore);
  }
}

在您发布的代码中,您实际上并不需要 seen 共享变量,因此我已将其删除。

【讨论】:

  • 编译器消息:lib/pages/score_page.dart:27:36:错误:意外令牌“等待”。最终 SharedPreferences 首选项 = await SharedPreferences.getInstance(); ^^^^^ lib/pages/score_page.dart:30:5: 错误:'await' 不是类型。等待 prefs.setInt('highScore', highscore); ^^^^^ lib/pages/score_page.dart:30:11: 错误:预期为 ';'在这之后。等待 prefs.setInt('highScore', highscore); ^^^^^ lib/pages/score_page.dart:30:16: 错误:需要一个标识符,但得到'.'。等待 prefs.setInt('highScore', highscore); ^
  • @PrakashKing 您只能在async 函数中使用await,这是其他地方的语法错误。详情请见dartlang.org/tutorials/language/futures
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多