如何正确将值保存在sharedPreferences中? -颤振

时间:2020-03-09 15:36:40

标签: flutter graphql sharedpreferences mobx hasura

我要去哪里错了? 我已使用google登录以获取令牌并将其发送到graphgl,此令牌已保存(本来是)在sharedpreferences中,但未保存,我有以下操作(mobx)。

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

服务已共享。

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
  Future loginWithGoogle() async {
    try {
      loading = true;
      await auth.loginWithGoogle();
      Modular.to.pushReplacementNamed('/index');
    } catch (e) {
      loading = false;
    }
  }

登录正常进行,但是在进入索引时会出错,通知其 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")

此令牌字符串未保存。 对不起,英语不好

2 个答案:

答案 0 :(得分:2)

只需复制代码并进行一些更改即可,只需检查一下即可:

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');
}

答案 1 :(得分:0)

非常感谢,我在操作中做了更正。

@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}');
    }
  }