Flutter: Access Stored Sharedpreference value from Other Pages

ε祈祈猫儿з 提交于 2019-12-17 14:22:31

问题


I'm storring a vlaue in a page1.dart,i want to access the stored value from page2.dart or page3.dart, How can i achive this??


回答1:


Flutter shared preferences is actually implemented as an in-memory cache. The first time that you call SharedPreferences.getInstance() all the current values are read from NSUserDefaults (on iOS) and SharedPreferences (on Android) and cached in memory. This involves channels, so is async. The Future returns a singleton class that wraps this cache. Any subsequent calls to getInstance return this singleton class.

When you get a value from shared preferences the value is simply fetched from the in-memory cache. When you set a value the cache is immediately updated and an async method started to write it back to the operating system. (You can wait for confirmation of completion of that, but you don't have to.) Note that the reads and writes from and to the cache are synchronous, so you have immediate access to that cache of settings. (It may take a moment to reach the operating system so the in-memory cache isn't guaranteed to match the device preferences, but this should only happen under error conditions.)

The reason why this is interesting is that once you get the result of SharedPreferences.getInstance() you can read and write values synchronously. Since the instance is singleton it seems reasonable to keep a copy of it. In particular, you can make your main async and fetch it there.

SharedPreferences sp;

void main() async {
  sp = await SharedPreferences.getInstance();
  runApp(new MyApp());
}

This allows you to refer to sp throughout your code:

  onPressed: () {
    sp.setString('abc', 'def');
  },

knowing that the in-memory cache is consistent. In particular, any values set in one page can be got in another page following navigation.

Having said all that, you should probably think of your stored preferences as just one part of your state, which just happens to get initialized at startup and on setting it fires off a background task to persist it automatically. You could then deal with the preferences in the same way as the rest of your state however you are doing that (InheritedWidget + controller, Redux, Streams, etc.).




回答2:


I have stored a string in 1st screen,then retrieved the stored value from the second screen by the following code

PAGE 1:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _email = '';

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _email = (prefs.getString('email') ?? '');
    });
  }

  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _email = "a@gmail.com";
    });
    prefs.setString('email', _email);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("title"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$_email',
            ),
            new RaisedButton(
              child: new Text("next2"),
              onPressed: () {
                Navigator.push(context,
                    new MaterialPageRoute(builder: (context) => new Next()));
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        child: Icon(Icons.add),
      ),
    );
  }
}

PAGE 2:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
String _email='';
class Next extends StatefulWidget {
  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
    @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _email = (prefs.getString('email')??'');
    });
  }
  @override
  Widget build(BuildContext context) {

    return Container(
      child: new Text("read value from sharepreference is:"+_email),
    );
  }
}


来源:https://stackoverflow.com/questions/51215064/flutter-access-stored-sharedpreference-value-from-other-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!