Я хочу добавить функцию высокой оценки в приложение для викторины и сохранить значение, используя общие настройки.Затем я хотел бы показать это пользователю, если он щелкнет значок на целевой странице.Я видел похожий вопрос, и пример кода для общих настроек, которые они дали, выглядел так:
Get:
Future<void> getHighScore() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
_highscore = prefs.getInt('highScore') ?? 0;
}
Set:
Future<void> setHighScore() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (_score > _highscore) {
_highscore = _score;
await prefs.setInt('highScore', _highscore);
}
}
В настоящее время япередать результаты каждого теста в ScorePage следующим образом:
if (quiz.length == questionNumber) {
Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (BuildContext context) => new ScorePage(quiz.score, quiz.length)), (Route route) => route == null);
return;
}
И я это понимаю.Но у меня возникают трудности с отображением значения хранилища или с сохранением и отображением значения.
quiz.dart (где я установил высокий балл)
import './question.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
class Quiz {
List<Question> _questions;
int _currentQuestionIndex = -1;
int _score = 0;
int _highScore; //new
Quiz(this._questions) {
_questions.shuffle();
}
List<Question> get questions => _questions;
int get length => _questions.length;
int get questionNumber => _currentQuestionIndex + 1;
int get score => _score;
Question get nextQuestion {
_currentQuestionIndex++;
if (_currentQuestionIndex >= length) return null;
return _questions[_currentQuestionIndex];
}
void answer (bool isCorrect) {
if (isCorrect) _score++;
}
Future<void> setHighScore() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
if (_score > _highScore) {
_highScore = _score;
await prefs.setInt('highScore', _highScore);
}
}
}
high_score_page.dart (где яполучить высокий балл)
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'landing_page.dart';
class HighScorePage extends StatefulWidget {
@override
_HighScorePageState createState() => _HighScorePageState();
}
class _HighScorePageState extends State<HighScorePage> {
int _highScore;
@override
void initState() {
super.initState();
_loadHighScore();
}
_loadHighScore() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_highScore = (prefs.getInt('highScore') ?? 0);
});
}
@override
Widget build(BuildContext context) {
return new Material(
color: Colors.blueAccent,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text("Your high score: ", style: new TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 50.0),),
Я пробовал разные вещи, такие как:
new Text(_highScore.toString() // always returns 0
new Text(_loadHighScore() // returns type Future<dynamic> is not a subtype of 'String'
new Text('$_highScore' // always returns 0
Мне удалось вывести только 0 или ошибка.