0

I have the class below which I set and get the bool value to remember the user and auto-login next time.

import 'package:shared_preferences/shared_preferences.dart';

class SettingHelper {
  static Future<bool> getValue(String key) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    var s = prefs.getBool(key);
    print("GetValue ${s.toString()}"); //prints "GetValue true"
    return s;
  }

  static Future<void> setValue(String key, bool value) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool(key, value);
  }
}

I set my value in Login page with a CheckBox value.

onPressed: () {
...
SettingHelper.setValue("rememberMe", checkBoxValue);
...
}

When I start debugging I saw setValue worked. But when I hot restart getValue returns null in initState() but returns true in function. Here is the code:

class LandingPage extends StatefulWidget {
  @override
  _LandingPageState createState() => _LandingPageState();
}

class _LandingPageState extends State<LandingPage> {
  bool rememberMe;

  void _getRememberMeChoice() async {
    rememberMe = await SettingHelper.getValue("rememberMe");
  }

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

  @override
  Widget build(BuildContext context) {
    print(rememberMe);  //Returns null
    if (rememberMe == true) {
      return BridgeList();
    } else
      return LoginScreen();
  }
}

These are the outputs:

I/flutter (11724): null
I/flutter (11724): GetValue true

Please tell me if I'm doing something wrong...

1 Answer 1

0

That's because you can't await a value inside initState()

In this case the build() function is executed before you get the rememberMe value.

Try adding a setState((){}) after the getValue(), so you do a rebuild.

Like this

void _getRememberMeChoice() async {
    rememberMe = await SettingHelper.getValue("rememberMe");
    setState((){})
  }

Also, notice that in the first build execution, the rememberMe value will be null. So you should add that validation in your if condition.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.