首页 > 解决方案 > Flutter shared_preferences 0.5.7 APP重新加载后无法获取值

问题描述

我在我的颤振项目中使用https://pub.dev/packages/shared_preferences,我发现有一些问题。简单来说,我刚设置了就可以拿价值,但是这个app重新加载之后就拿不到价值了。

然后我创建了一个全新的项目来测试共享偏好插件,就像一个计数器演示,它可以工作。APP重新加载后可以取值,但是我在实际项目中写了相同的代码,它不起作用,我只能在这个APP仍在运行时按键获取值,重新加载后,SharedPreferences的实例不包含任何内容。

我的真实项目比较复杂,所以我只是把我的demo项目放在这里,两个项目中共享首选项插件的用法是一样的。我在同一台设备上运行这两个项目。

任何帮助都非常感谢!

// main.dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final spKey = 'abc';
  String value;

  void getValue() async {
    print('getValue()');

    final sp = await SharedPreferences.getInstance();

    if (sp.containsKey(spKey)) {
      setState(() {
        value = sp.getString(spKey);
      });
    }
  }

  void setValue() async {
    print('setValue()');

    final sp = await SharedPreferences.getInstance();

    setState(() {
      sp.setString(spKey, '123');
    });
  }

  @override
  Widget build(BuildContext context) {
    print('build() value: $value');

    if (value == null) {
      getValue();
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You set value to:',
            ),
            Text(
              '$value',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: setValue,
        tooltip: 'Increment',
        child: Icon(Icons.refresh),
      ),
    );
  }
}

我的颤振医生是:

[✓] Flutter (Channel stable, v1.12.13+hotfix.9, on Mac OS X 10.14.6 18G103, locale en-CN)
    • Flutter version 1.12.13+hotfix.9 at /Volumes/Transcend/Development/flutter
    • Framework revision f139b11009 (5 weeks ago), 2020-03-30 13:57:30 -0700
    • Engine revision af51afceb8
    • Dart version 2.7.2

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
    • Android SDK at /Volumes/Transcend/Development/AndroidSDK
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.2
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.3.1, Build version 11C504
    • CocoaPods version 1.9.0

[✓] Android Studio (version 3.6)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 45.1.1
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

[✓] VS Code (version 1.44.2)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.10.1

[✓] Connected device (1 available)
    • Capt. Michael’s iPhone • 14717dae7626a115db93783c0f4a386e6c51783e • ios • iOS 12.4.5

• No issues found!

标签: fluttersharedpreferences

解决方案


通过删除一些无用的代码来解决。


推荐阅读