url static method
the path of the route named name, with its {params} filled in.
a param value is url encoded. query is added as the query string.
an unknown name or a missing param throws an ArgumentError.
Route.url('users.show', params: <String, Object>{'id': 5});
// /users/5
Implementation
static String url(
String name, {
Map<String, Object?> params = const <String, Object?>{},
Map<String, Object?> query = const <String, Object?>{},
}) {
RouteData? data = Route()._byName()[name];
if (data == null) {
throw ArgumentError.value(name, 'name', 'No route has this name');
}
Set<String> used = <String>{};
List<String> parts = <String>[];
for (String part in data.path.split('/')) {
if (!part.startsWith('{') || !part.endsWith('}')) {
parts.add(part);
continue;
}
bool rest = part.endsWith('*}');
bool optional = part.endsWith('?}');
String param = part
.substring(1, part.length - 1)
.replaceAll('*', '')
.replaceAll('?', '');
Object? value = params[param];
used.add(param);
if (value == null) {
if (optional) continue;
throw ArgumentError(
'Route "$name" (${data.path}) needs the param "$param".',
);
}
parts.add(
rest
? '$value'.split('/').map(Uri.encodeComponent).join('/')
: Uri.encodeComponent('$value'),
);
}
for (String key in params.keys) {
if (!used.contains(key)) {
throw ArgumentError(
'Route "$name" (${data.path}) has no param "$key". '
'Use query: for the query string.',
);
}
}
String path = parts.join('/');
if (path.isEmpty) path = '/';
if (query.isEmpty) return path;
Map<String, String> values = <String, String>{
for (MapEntry<String, Object?> entry in query.entries)
if (entry.value != null) entry.key: '${entry.value}',
};
if (values.isEmpty) return path;
return '$path?${Uri(queryParameters: values).query}';
}