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.
a param that is not in the path goes to the query string too. When
params and query have the same key, query wins. A null value
is left out. an unknown name or a missing param throws an
ArgumentError.
With absolute, baseUrl (default: APP_URL of the env, like
https://example.com) is put in front. It throws an ArgumentError
when there is no base url.
Route.url('users.show', params: <String, Object>{'id': 5});
// /users/5
Route.url('users.show', params: <String, Object>{'id': 5, 'tab': 'a'});
// /users/5?tab=a
Route.url('users.show', params: <String, Object>{'id': 5}, absolute: true);
// https://example.com/users/5
Implementation
static String url(
String name, {
Map<String, Object?> params = const <String, Object?>{},
Map<String, Object?> query = const <String, Object?>{},
bool absolute = false,
String? baseUrl,
}) {
RouteData? data = Route()._byName()[name];
if (data == null) {
throw ArgumentError.value(name, 'name', 'No route has this name');
}
Set<String> used = <String>{};
// every `{param}`, also in a part with text like `v{id}`
String path = data.path.replaceAllMapped(_urlParam, (Match match) {
String text = match[0]!;
String slash = text.startsWith('/') ? '/' : '';
String param = match[1]!.replaceAll('*', '').replaceAll('?', '');
Object? value = params[param];
used.add(param);
if (value == null) {
if (text.endsWith('?}')) return '';
throw ArgumentError(
'Route "$name" (${data.path}) needs the param "$param".',
);
}
if (text.endsWith('*}')) {
return slash + '$value'.split('/').map(Uri.encodeComponent).join('/');
}
return slash + Uri.encodeComponent('$value');
});
if (path.isEmpty) path = '/';
if (absolute) path = '${_baseUrl(baseUrl)}$path';
Map<String, String> values = <String, String>{
for (MapEntry<String, Object?> entry in <String, Object?>{
for (MapEntry<String, Object?> extra in params.entries)
if (!used.contains(extra.key)) extra.key: extra.value,
...query,
}.entries)
if (entry.value != null) entry.key: '${entry.value}',
};
if (values.isEmpty) return path;
return '$path?${Uri(queryParameters: values).query}';
}