chetan suri
chetan suri

Reputation: 399

Flutter save device token to SharedPreferences

I am trying to save device token to SharedPreferences so I can use it in other widgets, but token value is always coming as null in other widgets. Not sure what I am doing wrong here.

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _messaging.getToken().then((token)  {
      _getAndSaveToken;

        });

  }

 _getAndSaveToken()  {
    _messaging.getToken().then((token) async{
      final prefs = await SharedPreferences.getInstance();
      await prefs.setString('token', token);
      print(token);
    });

  }

Upvotes: 0

Views: 1483

Answers (1)

Suthura Sudharaka
Suthura Sudharaka

Reputation: 673

In order to use shared preferences first you have to create an instance like this

SharedPreferences prefs = await SharedPreferences.getInstance();

Then to save a value

prefs.setString("token", token);

To Access this file in another widget you should access the same instance and use get

String token = prefs.getString("token");

In your case to set the token it should be like this.

_getAndSaveToken() async {
    _messaging.getToken().then((token) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString("token", token);
      print(token);
    });    
  }

You can access this token like below

_getSavedToken() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        String token = prefs.getString("token");    // do something with this
      }

Upvotes: 2

Related Questions