Flutter:SharedPreferences在应用启动时未获取值 [英] Flutter : SharedPreferences not fetching value at app start

查看:1156
本文介绍了Flutter:SharedPreferences在应用启动时未获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图存储一个值,并根据该值导航到LandinPage或HomePage.但是,当我的应用加载时,我无法获取SharedPreferences值.目前,该值是在着陆页"上单击按钮时以及在我关闭/最小化该应用程序时设置的.我什至看不到来自main.dart的打印消息,并且无法获取值.我究竟做错了什么?

I am trying to store a value and based on the value I want to navigate to LandinPage or HomePage. However when my app loads I am not able to get the SharedPreferences value. Currently, the value is set on click of a button in Landing page, and when I close/minimize the app. I don't even get to see the print messages from main.dart and can't fetch values. What am I doing wrong?

这是我的代码:

import 'package:credit/src/pages/landing.dart';
import 'package:flutter/material.dart';
import 'package:credit/src/pages/credit/home.dart';
import 'package:shared_preferences/shared_preferences.dart';

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    getUserStatus().then((userStatus) {
      if (userStatus == null) {
        Navigator.of(context)
            .push(MaterialPageRoute<Null>(builder: (BuildContext context) {
          return LandingPage();
        }));
      } else {
        Navigator.of(context)
            .push(MaterialPageRoute<Null>(builder: (BuildContext context) {
          return HomePage();
        }));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Center(
      child: CircularProgressIndicator(),
    ));
  }
}

Future<String> getUserStatus() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String userStatus = prefs.getString('userstatus');
  print("==On Load Check ==");
  print(userStatus);
  return userStatus;
}

推荐答案

您可能需要使用首先在两个页面中的任何一个之前加载的加载页面":

You may need to use a "loading page" that is first loaded before any of your two pages:

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'An App',
      home: LoadingPage(),
      routes: {
        '/landing': (context) => LandingPage(),
        '/home': (context) => HomePage(),
      }
    );
  }
}


class LoadingPage extends StatefulWidget {
  LoadingPage({Key key}) : super(key: key);

  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  @override
  void initState() {
    super.initState();
     loadPage();
  }

  loadPage() {
     getUserStatus().then((userStatus) {
      if (userStatus == null) {
        Navigator.of(context).pushNamed('/landing');
      } else {
        Navigator.of(context).pushNamed('/home');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Center(
      child: CircularProgressIndicator(),
    ));
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Container(
       child: Text('Home Page'),
    );
  }
}

class LandingPage extends StatefulWidget {
  LandingPage({Key key}) : super(key: key);

  _LandingPageState createState() => _LandingPageState();
}


class _LandingPageState extends State<LandingPage> {

  @override
  void initState() {
    super.initState();
    setUserStatus('done');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Text('Landing'),
    );
  }
}

Future<String> getUserStatus() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String userStatus = prefs.getString('userStatus');
  print("==On Load Check ==");
  print(userStatus);
  return userStatus;
}

Future<bool> setUserStatus(String userStatus) async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('userStatus', userStatus);
  return true;
}

这篇关于Flutter:SharedPreferences在应用启动时未获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆