繁体   English   中英

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

[英]How to correctly save the value in sharedPreferences? - Flutter

我哪里错了? 我已使用谷歌登录以获取令牌并将其发送到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;
    }
  }

登录发生正常,但它在进入索引时指责错误,通知它收到了 null 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")

未保存此令牌字符串。 抱歉英语不好

刚刚复制了您的代码并进行了一些更改,只需检查:

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

非常感谢,我在行动中进行了更正。

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

如何保存列表<object>到 Flutter 中的 SharedPreferences?<div id="text_translate"><p> 我有一个最喜欢的音乐列表,我在第一次打开应用程序时从音乐中检索,该应用程序从收藏夹中获取最喜欢的音乐列表。 我想将此列表保存到共享</p><pre>preferences.List&lt;Music&gt; favoriteMusic = new List&lt;Music&gt;();</pre><p> 其中音乐 class 是:</p><pre> class Music { final int id; final String name, size, rating, duration, img; bool favorite; Music({ this.id, this.rating, this.size, this.duration, this.name, this.img, this.favorite, }); factory Music.fromJson(Map&lt;String, dynamic&gt; jsonData){ return Music( id: jsonData['id'], rating: jsonData['rating'], size: jsonData['size'], duration: jsonData['duration'], name: jsonData['name'], img: jsonData['img'], favorite: false, ); } }</pre><p> 如何保存最喜欢的音乐列表?</p></div></object>

[英]How to save List<Object> to SharedPreferences in Flutter?

Flutter 如何保存和显示列表<object>共享首选项?<div id="text_translate"><p> 我想保存并阅读一个名为 coursefav 的元素列表。</p><p> 我有以下代码,我在其中制作了 class 的 map,但我不知道如何保存字符串 map 的元素,然后在列表中一个一个地显示,然后在列表视图中显示所有元素。</p><p> 这就是我所拥有的</p><pre>//my class class curso { final String title; final String entidad; final String categoria; final String emision; final String imgcourse; final String urlcourse; final String idioma; final String duracion; final String description; curso({ required this.title, required this.entidad, required this.categoria, required this.emision, required this.imgcourse, required this.urlcourse, required this.idioma, required this.duracion, required this.description, }); Map&lt;String, dynamic&gt; toMap() { return { 'title': title, 'entidad': entidad, 'categoria': categoria, 'emision': emision, 'imgcourse': imgcourse, 'urlcourse': urlcourse, 'idioma': idioma, 'duracion': duracion, 'description': description, }; } curso.fromMap(Map&lt;String, dynamic&gt; res): title = res["title"], entidad = res["entidad"], categoria = res["categoria"], emision = res["emision"], imgcourse = res["imgcourse"], urlcourse = res["urlcourse"], idioma = res["idioma"], duracion = res["duracion"], description = res["description"]; @override String toString() { return 'curso{title: $title, entidad: $entidad, categoria: $categoria, emision: $emision, imgcourse: $imgcourse, urlcourse: $urlcourse, idioma: $idioma, duracion: $duracion, description: $description}'; } }</pre><p> 我就是这样称呼的</p><pre> void saveCourseFavSP(String title,String entidad,String categoria,String emision,String imgcourse,String urlcourse,String idioma,String duracion,String description) async { //init sharedpreferences SharedPreferences cursosFav = await SharedPreferences.getInstance(); //object variable to load the info final testCursoFav = curso( title: title, entidad: entidad, categoria: categoria, emision: emision, imgcourse: imgcourse, urlcourse: urlcourse, idioma: idioma, duracion: duracion, description: description); String json = jsonEncode(testCursoFav); print("generating json $json"); //sending all items object to sharedPreferences cursosFav.setString('coursesFavorites', json); //here i want to insert String to List&lt;Strin&gt; //sending String to something like.upperCase //but i dont know how to parse and how to read List&lt;String&gt; lista = jsonDecode(json); } loadDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); String? json = cursosFav.getString("coursesFavorites"); print("datos de curso favorito cargados:\n $json"); if (json == null) { print("Items doesn't exist"); } else { Map&lt;String, dynamic&gt; map = jsonDecode(json); final cursofav = curso.fromMap(map); print( "titulo fav: ${cursofav.title}, ${cursofav.entidad},${cursofav.emision},"); } } clearDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); cursosFav.clear(); print("ALL ITEMS LIST ARE DELETED"); }</pre></div></object>

[英]Flutter How to save and show List<Object> to SharedPreferences?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何正确使用 SharedPreferences flutter 如何在 Flutter 中使用 SharedPreferences 保存 DateFormat? 如何在 Flutter 的 SharedPreferences 中保存列表 Flutter:在 SharedPreferences 中保存和获取多个值 如何保存列表<object>到 Flutter 中的 SharedPreferences?<div id="text_translate"><p> 我有一个最喜欢的音乐列表,我在第一次打开应用程序时从音乐中检索,该应用程序从收藏夹中获取最喜欢的音乐列表。 我想将此列表保存到共享</p><pre>preferences.List&lt;Music&gt; favoriteMusic = new List&lt;Music&gt;();</pre><p> 其中音乐 class 是:</p><pre> class Music { final int id; final String name, size, rating, duration, img; bool favorite; Music({ this.id, this.rating, this.size, this.duration, this.name, this.img, this.favorite, }); factory Music.fromJson(Map&lt;String, dynamic&gt; jsonData){ return Music( id: jsonData['id'], rating: jsonData['rating'], size: jsonData['size'], duration: jsonData['duration'], name: jsonData['name'], img: jsonData['img'], favorite: false, ); } }</pre><p> 如何保存最喜欢的音乐列表?</p></div></object> Flutter 如何保存和显示列表<object>共享首选项?<div id="text_translate"><p> 我想保存并阅读一个名为 coursefav 的元素列表。</p><p> 我有以下代码,我在其中制作了 class 的 map,但我不知道如何保存字符串 map 的元素,然后在列表中一个一个地显示,然后在列表视图中显示所有元素。</p><p> 这就是我所拥有的</p><pre>//my class class curso { final String title; final String entidad; final String categoria; final String emision; final String imgcourse; final String urlcourse; final String idioma; final String duracion; final String description; curso({ required this.title, required this.entidad, required this.categoria, required this.emision, required this.imgcourse, required this.urlcourse, required this.idioma, required this.duracion, required this.description, }); Map&lt;String, dynamic&gt; toMap() { return { 'title': title, 'entidad': entidad, 'categoria': categoria, 'emision': emision, 'imgcourse': imgcourse, 'urlcourse': urlcourse, 'idioma': idioma, 'duracion': duracion, 'description': description, }; } curso.fromMap(Map&lt;String, dynamic&gt; res): title = res["title"], entidad = res["entidad"], categoria = res["categoria"], emision = res["emision"], imgcourse = res["imgcourse"], urlcourse = res["urlcourse"], idioma = res["idioma"], duracion = res["duracion"], description = res["description"]; @override String toString() { return 'curso{title: $title, entidad: $entidad, categoria: $categoria, emision: $emision, imgcourse: $imgcourse, urlcourse: $urlcourse, idioma: $idioma, duracion: $duracion, description: $description}'; } }</pre><p> 我就是这样称呼的</p><pre> void saveCourseFavSP(String title,String entidad,String categoria,String emision,String imgcourse,String urlcourse,String idioma,String duracion,String description) async { //init sharedpreferences SharedPreferences cursosFav = await SharedPreferences.getInstance(); //object variable to load the info final testCursoFav = curso( title: title, entidad: entidad, categoria: categoria, emision: emision, imgcourse: imgcourse, urlcourse: urlcourse, idioma: idioma, duracion: duracion, description: description); String json = jsonEncode(testCursoFav); print("generating json $json"); //sending all items object to sharedPreferences cursosFav.setString('coursesFavorites', json); //here i want to insert String to List&lt;Strin&gt; //sending String to something like.upperCase //but i dont know how to parse and how to read List&lt;String&gt; lista = jsonDecode(json); } loadDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); String? json = cursosFav.getString("coursesFavorites"); print("datos de curso favorito cargados:\n $json"); if (json == null) { print("Items doesn't exist"); } else { Map&lt;String, dynamic&gt; map = jsonDecode(json); final cursofav = curso.fromMap(map); print( "titulo fav: ${cursofav.title}, ${cursofav.entidad},${cursofav.emision},"); } } clearDataCursosFavSP() async { SharedPreferences cursosFav = await SharedPreferences.getInstance(); cursosFav.clear(); print("ALL ITEMS LIST ARE DELETED"); }</pre></div></object> 如何在 SharedPreferences flutter 中保存列表数据 如何保存列表<list<string> &gt; 在 Flutter 中使用 SharedPreferences </list<string> Flutter 在 SharedPreferences 上保存 Object 如何在 Flutter/Dart 中显示 SharedPreferences 值?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM