Search code examples
fluttersharedpreferencesandroid-bottomappbar

How to get shared preferences data before widget build?


I have a few textfields with hint text and bottom navigation. Text entered into the textfield (in Page 1) will be saved to shared preferences "on changed".

When I click on the bottom navigation next page (Page 2) and back to Page 1 again, it seems like the widget rebuild and will show the hintText before shared preference stored data display on the widget.

I have tried to get the sharedpreference data during initState but it does not work. I have also tried to use future builder however when I typed the value in the TextField is not that smooth, sometimes the text would flicker between the characters before and after. I am not sure which method should I use or whether is my my coding wrong.

Could someone advise which method should I use?

Thanks in advance!

login.dart

  @override
  Widget build(BuildContext context){

    return new Scaffold(
        appBar: new AppBar(
          title: Text('Login Page'),
        ),

        body: bottomNav[currentBottomNavIndex],

        bottomNavigationBar: BottomNavigationBar(
          onTap: onTapped,
          currentIndex: currentBottomNavIndex,
          type: BottomNavigationBarType.fixed,
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text("Page1"),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.mail),
              title: Text('Page2'),
            ),
          ],
        ),


    );

  }

page1.dart

class Page1 extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _Page1State();
  }
}

class _Page1State extends State<Page1> {

  TextEditingController name = TextEditingController();

  String name_str;

  Future<String> getName(String key) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    name_str = prefs.getString(key);

    setState(() {
      name = new TextEditingController(text: name_str);
    });

    return name_str;
  }

  Future<bool> setName(String key, String value) async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();

    return prefs.setString(key, value);
  }

  @override
  void initState() {
    super.initState();
    getName('name');
  }


  @override
  Widget build(BuildContext context) {


   //return FutureBuilder(

        //future: getName('name'),
        //builder: (BuildContext context, AsyncSnapshot<String> snapshot) {

        //      if (snapshot.hasData) {

                return Container(

                    margin: EdgeInsets.all(100.0),
                    width: 185,
                    child: Center(
                        child: TextField(

                          controller: name,
                          textAlign: TextAlign.center,
                          decoration: new InputDecoration(
                            hintText: "Name (Original)",
                          ),

                          onTap:() {
                            name.clear();
                            setName('name', '');

                          },

                          onChanged: (String str) {
                            setState(() {
                              name_str = str;
                              setName('name', str);
                            });
                          },
                        )
                    )
                );
     //         }else{
     //           return Container();
     //         }

     //   }
    //);

  }
}

Page2.dart

class Page2 extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Text('Page2'),
      ),
    );
  }
}

Solution

  • I think the problem resides here

    setState(() {
      name = new TextEditingController(text: name_str);
    });
    

    doing this

    new TextEditingController(text: name_str);

    will create a new instance instead just update the value of name controller using shared preferences.

     setState(() {
          name.text=name_str;
        });
    

    This should work for you