【问题标题】:Flutter Shared Preferences Auth FIleFlutter Shared Preferences Auth 文件
【发布时间】:2019-08-27 12:32:16
【问题描述】:

我正在尝试编写一个身份验证文件,其中包含一个包含共享首选项值的决赛列表。我可以在我的其他文件中导入该身份验证文件,并且无需在每个文件中导入共享首选项即可获得名称或电子邮件。

它可能看起来更平滑、更干净。

我认为这样的事情会奏效,但它没有

/// ------------Auth------------ ///
final email = getEmail();

getEmail() async {
  final SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('email');
}

有人知道怎么做吗?

您好, 珍特

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    我假设您想在多个文件中使用该方法。您的代码的问题在于 getEmail 方法标记为 async,这意味着它必须返回 Future。可以这样想,当您将方法标记为async 时,这意味着它将在不久的将来返回某些内容(或完成执行)。什么时候 ?好吧,您不知道确切的时间,因此您需要在方法“完成”时得到“通知”,这就是您将使用Future 的原因。像这样的:

    Future<String> getEmail() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      return prefs.getString('email');
    }
    
    class ThisIsTheClassWhereYouWantToUseTheFunction {
       //let's say you have a method in your class called like the one below (it can be any other name)
      void _iNeedTheEmailToPrintIt() {
         //this is the way you can call the method in your classes, this class is just an example.
         getEmail().then((thisIsTheResult){ // here you "register" to get "notifications" when the getEmail method is done.
            print("This is the email $thisIsTheResult");
         });
      }
    }
    

    【讨论】:

    • @SJente 这是我这边的错误复制/粘贴/编辑。检查编辑的答案。
    • 啊,是的,这看起来更好。我应该如何在我的其他文件中调用它来获取电子邮件?
    • @SJente SomeRandomClass 展示了如何从其他类调用它。只需要导入添加函数的文件即可。
    • 很抱歉,我真的不明白你的意思。我将此身份验证文件导入我的其他文件中。那我想我需要打电话给 SomeRandomClass 吗?但是然后呢?
    • @SJente 是的,它可能会有点混乱,我在代码中添加了一些额外的 cmets,也许它们可以帮助你:)。
    【解决方案2】:

    您可以定义一个类 Auth 或更好的 scoped_model

    这是一个类的实现

    class Auth {
       get email() {
           final SharedPreferences prefs = await SharedPreferences.getInstance();
           return prefs.getString('email');  
       }
    
       set email(String em) {
           final SharedPreferences prefs = await SharedPreferences.getInstance();
           pref.setString('email', em);
       }
    
    }
    
    and now you can call it in your widgets :)
    
    
    

    【讨论】:

      【解决方案3】:

      试试这个;

      1. 制作 dart 文件(文件名和类名 ShareUtils)

      添加关注代码

      import 'package:shared_preferences/shared_preferences.dart';
      import 'dart:async';
      
      class ShareUtils {
        static ShareUtils _instance;
        SharedPreferences ShareSave;
      
        factory ShareUtils() => _instance ?? new ShareUtils._();
      
        ShareUtils._();
      
        void Instatce() async {
          ShareSave = await SharedPreferences.getInstance();
        }
      
        Future<bool> set(key, value) async {
          return ShareSave.setString(key, value);
        }
      
        Future<String> get(key) async {
          return ShareSave.getString(key);
        }
      }
      

      2.添加main.dart

      class MyApp extends StatelessWidget {
        static ShareUtils shareUtils;
      
        @override
        Widget build(BuildContext context) {
          ThemeData mainTheme = new ThemeData(
          );  
          shareUtils = new ShareUtils();
          shareUtils.Instatce();
          MaterialApp mainApp = new MaterialApp(
            title: "Your app",
            theme: mainTheme,
            home: new SplashPage(),
            debugShowCheckedModeBanner: true,
            routes: <String, WidgetBuilder>{
             "RegisterPage": (BuildContext context) => new RegisterPage(),
             "HomePage": (BuildContext context) => new HomePage(),         
           },
         );
          return mainApp;
        }
      }
      

      3.SET

      void UserInfo(code, token) async{
          await MyApp.shareUtils.set("token", token);
          await MyApp.shareUtils.set("code", code);
          await Navigator.of(context).pushNamed("HomePage");
      }
      

      4.GET

      Future NextPage() async {
      MyApp.shareUtils.get("token").then((token) {
        print(token);
        if (token == null || token == "") {
          Navigator.of(context).popAndPushNamed("RegisterPage");
        } else {
          Navigator.of(context).popAndPushNamed("HomePage");
        }
      });
      

      }

      希望能提供帮助。

      【讨论】:

        猜你喜欢
        • 2020-10-07
        • 2019-02-11
        • 1970-01-01
        • 1970-01-01
        • 2019-08-27
        • 1970-01-01
        • 2012-11-21
        • 2021-06-23
        • 2021-03-29
        相关资源
        最近更新 更多