简体   繁体   中英

How to correctly save the value in sharedPreferences? - Flutter

Where am I going wrong? I have login with google to get the token and send it to graphgl, this token is saved (it was meant to be) in sharedpreferences, but it is not saving, I have the following action (mobx).

@action
Future loginWithGoogle() async {
 user = await _authRepository.getGoogleLogin();
 final idToken = await user.getIdToken();
 print('Bearer ${idToken.token}');
 sharedPreferenceService.setToken('Bearer ${idToken.token}');
}

Services shared.

class SharedPreferenceService {
  SharedPreferences _prefs;

  Future<bool> getSharedPreferencesInstance() async {
    _prefs = await SharedPreferences.getInstance().catchError((e) {
      print("shared prefrences error : $e");
      return false;
    });
    return true;
  }

  Future setToken(String token) async {
    await _prefs.setString('token', token);
  }

  Future clearToken() async {
    await _prefs.clear();
  }

  Future<String> get token async => _prefs.getString('token');
}

SharedPreferenceService sharedPreferenceService = SharedPreferenceService();

Action login in view.

@action
  Future loginWithGoogle() async {
    try {
      loading = true;
      await auth.loginWithGoogle();
      Modular.to.pushReplacementNamed('/index');
    } catch (e) {
      loading = false;
    }
  }

The login happens normal but it accuses error when it goes to index, informing that it received null the getString("token") .

I/flutter ( 3198): ClientException: Unhandled Failure NoSuchMethodError: The method 'getString' was called on null.
I/flutter ( 3198): Receiver: null
I/flutter ( 3198): Tried calling: getString("token")

This token string is not being saved. Sorry for bad english

Just copied your code and made some changes just check:

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  SharedPreferenceService sharedPreferenceService = SharedPreferenceService();

  @override
  void initState() {
    super.initState();
    loginWithGoogle();
    getSharedValues();
  }

  getSharedValues() async{
     bool value = await sharedPreferenceService.getSharedPreferencesInstance();
    if(value)
    print(await sharedPreferenceService.token);
  }

  loginWithGoogle() async {
    // this is the where you get your bearer, but time being I have taken sample bearer
    String token =
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJZb3VuaXNaYXJnYXIiLCJlbWFpbCI6InlvdW5pc0BiYXh0dXJlLmNvbSIsImp0aSI6IjlhNjc2OTVlLTBiZmEtNDdmMy04ZTVlLWVhYWMzY2VmNmRlOSIsIklkIjoiMSIsIkVtYWlsIjoieW91bmlzQGJheHR1cmUuY29tIiwiZXhwIjoxNTgzODQ2ODU0LCJpc3MiOiJQYWNpZmljIFByaW50aW5nIiwiYXVkIjoiUGFjaWZpYyBQcmludGluZyJ9.CKxBwAB7YeOKJRmoCg4_JAhJKHP2qXb7KJXPysqmbAs';

    bool value = await sharedPreferenceService.getSharedPreferencesInstance();
    if (value == true) {
      sharedPreferenceService.setToken('Bearer $token');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: Center(child: Text('sample'))));
  }
}

class SharedPreferenceService {
  SharedPreferences _prefs;

  Future<bool> getSharedPreferencesInstance() async {
    _prefs = await SharedPreferences.getInstance().catchError((e) {
      print("shared prefrences error : $e");
      return false;
    });
    return true;
  }

  Future setToken(String token) async {
    await _prefs.setString('token', token);
  }

  Future clearToken() async {
    await _prefs.clear();
  }

  Future<String> get token async => _prefs.getString('token');
}

Thank you very much, I made the correction in the action.

@action
  Future loginWithGoogle() async {
    user = await _authRepository.getGoogleLogin();
    final idToken = await user.getIdToken();
    print('Bearer ${idToken.token}');
    bool value = await sharedPreferenceService.getSharedPreferencesInstance();
    if (value == true) {
      sharedPreferenceService.setToken('Bearer ${idToken.token}');
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM