方法 'getString' 在 null 上被调用。接收者:null 尝试调用:getString("UserType")

时间:2021-06-24 17:30:18

标签: flutter dart

我首先在我的 flutter 应用程序中创建了 Global SharedPrefrence 它工作正常,但是当我关闭应用程序并再次重新打开时,我遇到了这个错误。

The following NoSuchMethodError was thrown building HomePage(dirty, state: _HomePageState#1e763):
    The method 'getString' was called on null.
    Receiver: null
    Tried calling: getString("UserType")

Here is SharedPreference service class

import 'dart:async' show Future;
    import 'package:shared_preferences/shared_preferences.dart';

    class PreferenceUtils {
      static Future<SharedPreferences> get _instance async => _prefsInstance ??= await SharedPreferences.getInstance();
      static SharedPreferences _prefsInstance;

      // call this method from iniState() function of mainApp().
      static Future<SharedPreferences> init() async {
        _prefsInstance = await _instance;
        return _prefsInstance;
      }

      static String getString(String key, [String defValue]) {
        return _prefsInstance.getString(key) ?? defValue ?? "";
      }

      static Future<bool> setString(String key, String value) async {
        var prefs = await _instance;
        return prefs?.setString(key, value) ?? Future.value(false);
      }
    }

I Initialize this class from my initState() of main class

class _MyappState extends State<Myapp> {
  @override
  void initState() {
    super.initState();
    PreferenceUtils.init();
  }

Here is how I insert value to SharedPreference Key 

    PreferenceUtils.setString("UserType", ownerSnapshot.data()['Account type'].toString());
    PreferenceUtils.setString("UserId",workerSnapshot.data()['userId'].toString());

这是我实际尝试使用这些 SharedPreference 的地方,我称之为 getString('UserType') 为了从 SharedPreference 中获取 UserType 的值,

      @override
      Widget build(BuildContext context) {
        String UserTypes = PreferenceUtils.getString("UserType");

      if(isSignedIn){
     if(UserTypes=='owner'){
       return buildagentScreen();
    
     } else if(UserTypes== 'Seller'){
       return buildHomeScreen();
         }else{
       return buildSignedInScreen();
     }
    
      }
      }

这是我尝试重新打开应用程序时遇到的错误

 The following NoSuchMethodError was thrown building HomePage(dirty, state: _HomePageState#1e763):
    The method 'getString' was called on null.
    Receiver: null
    Tried calling: getString("UserType")
    
    The relevant error-causing widget was: 
      HomePage HomePage:file:///C:/Users/likec/OneDrive/Desktop/project%20file/nethouese/lib/main.dart:61:29
    When the exception was thrown, this was the stack: 
    #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:63:5)
    #1      PreferenceUtils.getString (package:nethouese/pages/imported/pages/SharedPreferences.dart:15:27)
    #2      _HomePageState.build (package:nethouese/pages/imported/pages/HomePage.dart:70:40)
    #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4775:27)

0 个答案:

没有答案