toUri static method
Converts an object to a Uri.
- If the object is a string representing a valid URI, it converts it to a Uri object.
- If the object is
null
, throws aParsingException
with anullObject
error. - If the conversion to Uri fails (e.g., if the string is not a valid URI), throws a
ParsingException
.
object
The object to be converted to a Uri. Expected to be a string representing a URI.
mapKey
(Optional) Specifies the key to extract values from a Map object.
listIndex
(Optional) Specifies the index to extract elements from a List object.
Returns a Uri if conversion is successful.
Throws a ParsingException
if the conversion fails or the object is null.
Example usage:
final object1 = 'https://www.example.com';
final uri1 = ConvertObject.toUri(object1); // Uri.parse('https://www.example.com')
final object2 = 'invalid_uri';
final uri2 = ConvertObject.toUri(object2); // throws ParsingException
final object3 = null;
final uri3 = ConvertObject.toUri(object3); // throws ParsingException
Implementation
static Uri toUri(
dynamic object, {
dynamic mapKey,
int? listIndex,
}) {
if (object == null) {
throw ParsingException.nullObject(
parsingInfo: 'toUri',
stackTrace: StackTrace.current,
);
}
if (object is Uri) return object;
if (mapKey != null && object is Map<dynamic, dynamic>) {
return toUri(object[mapKey]);
}
if (listIndex != null && object is List<dynamic>) {
return toUri(object.of(listIndex));
}
try {
final ob = object.toString();
if (ob.isValidPhoneNumber) return ob.toPhoneUri;
return ob.toUri;
} catch (e, s) {
throw ParsingException(
error: e,
parsingInfo: 'toUri',
stackTrace: s,
);
}
}