blackbird
blackbird

Reputation: 500

How to load data stored in SharedPreference in flutter

I have a code for getting current logged in username and save it to a shared preference. The issue am facing is that whenever a user logs in for the first time, the username is never displayed, but when I do ahot reload on the app, the username is displayed on the screen . How can I have it in such a way the username is loaded on the first load without doing a hot reload.

How am getting the username on SharedPreference

/// Gets the current and prior accounts.
  Future<dynamic> handleGetAccount() async { // <-- Replace dynamic with type of currentAccount

    final result = await msal.getAccount();
    if (result.currentAccount != null) {
      SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
      sharedPreferences.setString("username", result.currentAccount.username);
      //print(result.currentAccount.username);
      return result.currentAccount;

    } else {
      print('no account found');
      return null;
    }
  }

My navigation to NavScreen ->redirects to Home screen

 /// Updates the signed in state

  refreshSignedInStatus() async {
    bool loggedIn = await msal.getSignedIn();
    if (loggedIn) {
      isSignedIn = loggedIn;
      if(isSignedIn) {
        Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => NavScreen(
            ),
          ),
        );
      }
      // Remaining code for navigation
    }
  }

how I am getting the username to show on home screen and show the username

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

  @override
  HomeState createState() => new HomeState();
}

class HomeState extends State<Home> {
  final TrackingScrollController _trackingScrollController =
      TrackingScrollController();
  String username = "";

  @override
  void initState() {
    getName();
  }

  Future<String> getName() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    username = prefs.getString("username");
    return username;
  }

Upvotes: 2

Views: 1591

Answers (1)

zhpoo
zhpoo

Reputation: 826

Because getName() is a async method, you should call setState((){}) after username got.

void getName() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  username = prefs.getString("username");
  setState((){});
}

Upvotes: 4

Related Questions