存储和使用共享偏好扑检索整数值

问题描述 投票:0回答:1

我想一个高分功能添加到测验的应用程序,并使用共享偏好保留价值。那么我想,如果他们点击登录页面上的图标来显示这个返回给用户。我已经看到了类似的问题问及他们给了这个样子共享偏好的代码示例:

得到:

  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
1个回答
0
投票

首先,我不认为你应该要使用它,每次申报一个共享的偏好。

我创建了一个模板,在以下地址创建“简单的在线应用程序”:

https://github.com/lhcdims/fluttertemplate02

它的特点之一是如何利用SharedPreferences。

PLS。注意3个功能:初始化(),GetString的()的SetString()GlobalVariable.dart,类GV内部关于如何定义功能对所有的get / set字符串。你可以写你自己的的get / set整数。

也看到在main()内main.dart如何使用的功能。

顺便说一句,你迟早会发现setstate这()不是所有类型的应用程序的一个很好的解决方案,你会使用联盟或终极版是最后的模板还演示了如何使用终极版。

© www.soinside.com 2019 - 2024. All rights reserved.