Home > Enterprise >  Saving Token in a Flutter Secure Storage not working properly
Saving Token in a Flutter Secure Storage not working properly

Time:11-14

I am trying to save a Token variable in a LoginResponseModel but I am getting:

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

Here is the 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?

CodePudding user response:

Because fromJson() is not an async function, so you cannot use await inside. You should write to the storage in another part, like repository.

CodePudding user response:

/// 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;
        }
      }
  • Related