Moji
Moji

Reputation: 1830

shared_preferences returns null on existing value

I am trying to see if an id key is available in my app's shared_pereferences and if there is, redirect my user to the homepage. I am checking the Id in the initState() function of my main.dart and I know that the id exists because I can get it in other pages. but in my main.dart it returns null. any ideas? here is my main.dart code:

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

import './ui/pages/auth/auth_one.dart';
import './ui/pages/main_page.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  SystemChrome.setPreferredOrientations(
          [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp])
      .then((_) => runApp(MyApp()));
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String userId;
  @override
  void initState() {
    _getUserId().then((id) => userId = id);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    print(userId);
    return MaterialApp(
      theme: ThemeData(primarySwatch: Colors.deepPurple),
      debugShowCheckedModeBanner: false,
      home: userId == null ? AuthOne() : MainPage(),
    );
  }

  _getUserId() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var id = prefs.getString('id');
    return id;
  }
}

Upvotes: 2

Views: 3015

Answers (2)

CodeforCore
CodeforCore

Reputation: 691

This is happening because you are trying to use the value before its calculated.

you could use timer function for delay

Upvotes: 2

diegoveloper
diegoveloper

Reputation: 103421

Your _getUserId method is async, so you will have to refresh the widget after you get the result.

Use this:

         @override
          void initState() {
            _getUserId().then((id) { 
              //calling setState will refresh your build method.
              setState(() {
                userId = id;
              });
            });
            super.initState();
          }

Upvotes: 2

Related Questions