Credentials.fromJson constructor Null safety

  1. String json

Loads a set of credentials from a JSON-serialized form.

Throws a FormatException if the JSON is incorrectly formatted.


factory Credentials.fromJson(String json) {
  void validate(bool condition, message) {
    if (condition) return;
    throw FormatException('Failed to load credentials: $message.\n\n$json');

  dynamic parsed;
  try {
    parsed = jsonDecode(json);
  } on FormatException {
    validate(false, 'invalid JSON');

  validate(parsed is Map, 'was not a JSON map');

  parsed = parsed as Map;
      'did not contain required field "accessToken"');
    parsed['accessToken'] is String,
    'required field "accessToken" was not a string, was '

  for (var stringField in ['refreshToken', 'idToken', 'tokenEndpoint']) {
    var value = parsed[stringField];
    validate(value == null || value is String,
        'field "$stringField" was not a string, was "$value"');

  var scopes = parsed['scopes'];
  validate(scopes == null || scopes is List,
      'field "scopes" was not a list, was "$scopes"');

  var tokenEndpoint = parsed['tokenEndpoint'];
  Uri? tokenEndpointUri;
  if (tokenEndpoint != null) {
    tokenEndpointUri = Uri.parse(tokenEndpoint as String);

  var expiration = parsed['expiration'];
  DateTime? expirationDateTime;
  if (expiration != null) {
    validate(expiration is int,
        'field "expiration" was not an int, was "$expiration"');
    expiration = expiration as int;
    expirationDateTime = DateTime.fromMillisecondsSinceEpoch(expiration);

  return Credentials(
    parsed['accessToken'] as String,
    refreshToken: parsed['refreshToken'] as String?,
    idToken: parsed['idToken'] as String?,
    tokenEndpoint: tokenEndpointUri,
    scopes: (scopes as List).map((scope) => scope as String),
    expiration: expirationDateTime,