Search code examples
flutterdartsharedpreferences

Get value from SharedPreferences without future builder


I need to get one stored value from shared preferences and put it into text widget. How can I do this without a future builder?

_currPage() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  int page = prefs.getInt('currPage') ?? 0;
  return page;
}
class _AllTasksPageState extends State<AllTasksPage> {
  @override
  Widget build(BuildContext context) {
  ...
  Text(_currPage()); //not working
  ...
  }
}

Solution

  •   int page = 0;
    
      @override
      void initState() {
        super.initState();
        readData();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Text('$page'),
          ),
        );
      }
    
      void readData() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        if (prefs.getInt('currPage') == null)
          setState(() => page = 0);
        else
          setState(() => page = prefs.getInt('currPage')!);
      }