简体   繁体   English

在 Flutter 安全存储中保存令牌无法正常工作

[英]Saving Token in a Flutter Secure Storage not working properly

I am trying to save a Token variable in a LoginResponseModel but I am getting:我试图在LoginResponseModel中保存 Token 变量,但我得到:

Error: 'await' can only be used in 'async' or 'async*' methods.
    await storage.write(key: 'Token', value: mapOfBody['key']);
    ^^^^^

Here is the Class:这是 Class:

class LoginResponseModel {
  dynamic? key;
  List<dynamic>? non_field_errors;
  LoginResponseModel({this.key, this.non_field_errors});

  LoginResponseModel.fromJson(mapOfBody) {
    key:
    mapOfBody['key'];
    non_field_errors:
    mapOfBody['non_field_errors'];
    print(mapOfBody['key']);

    // Create storage

    final storage = const FlutterSecureStorage();
    // Write value
    await storage.write(key: 'Token', value: mapOfBody['key']);
  }

  Map<String, dynamic> toJson() {
    final _data = <String, dynamic>{};
    _data['key'] = key;
    _data['non_field_errors'] = non_field_errors;
    return _data;
  }
}

to access the value:访问值:

var value = LoginResponseModel.storage.read(key: 'Token');

How can I fix the await problem so that I can easily access the token?如何解决等待问题以便我可以轻松访问令牌?

Because fromJson() is not an async function, so you cannot use await inside.因为fromJson()不是async function,所以不能在里面使用await You should write to the storage in another part, like repository.您应该写入另一部分的存储,例如存储库。

/// try out this way /// 尝试这种方式

static Future<LoginResponseModel> loginApiCall() async {
        try {
          var result = await http.get(Uri.parse('Your Url'));
          LoginResponseModel dataModel = LoginResponseModel.fromJson(result);
          await storage.write(key: 'Token', value: dataModel.token);
          return dataModel;
        } catch (e) {
          rethrow;
        }
      }

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

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