【问题标题】:Store and retrieve integer value in Flutter using shared preferences使用共享首选项在 Flutter 中存储和检索整数值
【发布时间】: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


    【解决方案1】:

    首先,我认为你不应该在每次使用共享偏好时都声明它。

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

    https://github.com/lhcdims/fluttertemplate02

    它的一个特点是如何使用 SharedPreferences。

    请。注意 GlobalVariable.dart 的 gv 类中的 3 个函数:Init()、getstring()、setstring(),了解如何为所有 get/set 字符串定义函数。您可以自己编写获取/设置整数。

    还可以查看 main.dart 中的 main() 了解如何使用这些函数。

    顺便说一句,你迟早会发现 setstate() 并不是适用于所有类型的 App,你最终会使用 BloC 或 Redux,模板还演示了如何使用 Redux。

    【讨论】:

      猜你喜欢
      • 2017-07-29
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2013-09-16
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多