3

I am adding some data into the SharedPreferenceson page2 of my app and I am trying to retrieve the data on the homepage. I have used an init function on page 1 as follows:

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

    _getrecent();
  }

  void _getrecent() async {
    final prefs = await SharedPreferences.getInstance();
    // prefs.clear();
    String b = prefs.getString("recent").toString();
    Map<String, dynamic> p = json.decode(b);

    if (b.isNotEmpty) {
      print("Shared pref:" + b);
      setState(() {
        c = Drug.fromJson(p);
      });
      cond = true;
    } else {
      print("none in shared prefs");
      cond = false;
    }
  }

Since the initState() loads only once, I was wondering if there was a way to load it every time page1 is rendered. Or perhaps there is a better way to do this. I am new to flutter so I don't have a lot of idea in State Management.

ag2byte
  • 191
  • 3
  • 11

4 Answers4

1

you can override didChangeDependencies method. Called when a dependency of the [State] object changes as you use the setState,

@override
  void didChangeDependencies() {
// your codes
}

Also, you should know that using setState updates the whole widget, which has an overhead. To avoid that you should const, declaring a widget const will only render once so it's efficient.

Sifat Amin
  • 1,091
  • 6
  • 15
0

You simply use setState() methode if you want to update widget. Here's documentation for this https://api.flutter.dev/flutter/widgets/State/setState.html

Sn1cKa
  • 601
  • 6
  • 11
0

First thing is you can't force initState to rebuild your widget. For that you have setState to rebuild your widget. As far as I can understand you want to recall initState just to call _getrecent() again.

Here's what you should ideally do :

A simple solution would be to use FutureBuilder. You just need to use _getrecent() in FutureBuilder as parent where you want to use the data you get from _getrecent(). This way everytime your Widget rebuilds it will call _getrecent().

Shubhamhackz
  • 7,333
  • 7
  • 50
  • 71
  • Should I change the return type of `_getrecent()` to something other than `void` ? – ag2byte Jun 29 '21 at 06:16
  • As I can see in the code you shared that you're using `c = Drug.fromJson(p);` value somewhere in your widget. Ideally you should return this value and wrap `FutureBuilder` to the widget which needs this value. – Shubhamhackz Jun 29 '21 at 06:58
0

init function will render it only once initially, to avoid that -

You can use setState( ) method to re-render your whole widget.

anirudh
  • 1,436
  • 5
  • 18