getVariable<T> method Null safety

T? getVariable<T>(
  1. {String? id,
  2. Type? type}
)

Gets variable by type and id.

Lets query for context variables by id and type. The variables are added using addVariable method in middleware or route handler.

Implementation

T? getVariable<T>({String? id, Type? type}) {
  type ??= T;
  Map<String, dynamic>? map = _variables[type];
  if (map != null) {
    if (id == null)
      return map.values.first;
    else {
      if (map.containsKey(id)) return map[id];
    }
  }

  if (id == null) {
    if (T == dynamic) {
      return null;
    }

    for (map in _variables.values) {
      for (dynamic v in map.values) {
        if (v is T) return v;
      }
    }
  } else {
    for (map in _variables.values) {
      if (!map.containsKey(id)) continue;
      if (map[id] is T) return map[id];
    }
  }

  return null;
}