android - 如何在 flutter 中为测验/游戏设置高分?

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

第一次打开设置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/

相关文章:

flutter - 如何在Flutter或Dart中将字符串编码为RFC 3986?

android - Google play 游戏服务,确定主机或服务器

java - 我需要什么才能开始创建类似于《部落冲突》的 Android 游戏?

android - 如何删除表的所有内容以及如何在 Eclipse 或 Android Emulator 中查看数据库

android - 颠簸android项目的版本号但不是每个构建

android-studio - flutter 有必要安装 Android Studio 还是可以用什么来代替 android studio?

git - 如何使用 ssh 访问 flutter 中的私有(private) repo 包?

android - 在使用 Google Apps 帐户登录时,在 Android 上对 Google Play 游戏服务进行身份验证会导致错误

java - Kotlin - 如何在 Kotlin 中不使用科学记数法将 Double 转换为 String?

java - 在 java 中使用方法避免 != null