第一次打开设置high score为0,flutter 它将检查分数并更新其值。 我也使用了共享首选项,但它不起作用。
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;
}
}
}
这总是返回我的分数和高分作为相同的值(数字)。告诉我解决方案
最佳答案
如果我正确理解您要执行的操作,您需要按如下方式编辑 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
共享变量,因此我已将其删除。
关于android - 如何在 flutter 中为测验/游戏设置高分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53104477/