【发布时间】:2019-06-27 18:32:54
【问题描述】:
我想向测验应用程序添加高分功能并使用共享偏好保留其价值。然后,如果用户单击登录页面上的图标,我想将其显示给用户。我看过一个类似的问题,他们给出的共享偏好的代码示例如下所示:
获取:
Future<void> getHighScore() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
_highscore = prefs.getInt('highScore') ?? 0;
}
设置:
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 或错误。
【问题讨论】:
标签: flutter sharedpreferences flutter-dependencies