parse static method
Parses a deep link URL and extracts route and payload information.
url - The deep link URL to parse (e.g., myapp://home?id=123, https://example.com/profile/456)
Returns a DeepLinkResult containing the parsed route and query parameters.
Example:
final result = DeepLinkParser.parse('myapp://product?id=123&name=Widget');
print(result.route); // '/product'
print(result.queryParams); // {'id': '123', 'name': 'Widget'}
Implementation
static DeepLinkResult parse(String url) {
if (url.isEmpty) {
return DeepLinkResult(route: '/', queryParams: {});
}
// Remove whitespace
url = url.trim();
// Handle custom schemes (e.g., myapp://path/to/route?id=123)
Uri? uri;
try {
uri = Uri.parse(url);
} catch (e) {
// If parsing fails, treat as path-only
return DeepLinkResult(route: url, queryParams: {});
}
// Extract path (route)
// For custom schemes like notificationapp://product/123,
// Uri.parse treats "product" as host, so we need to combine host and path
String route;
// Check if this is a custom scheme (not http/https)
final isCustomScheme = uri.scheme.isNotEmpty &&
uri.scheme != 'http' &&
uri.scheme != 'https';
if (isCustomScheme && uri.host.isNotEmpty) {
// For custom schemes, host is part of the path
// e.g., notificationapp://product/123 -> host="product", path="/123"
// Combine host and path: /product/123
final pathPart = uri.path.isEmpty || uri.path == '/' ? '' : uri.path;
route = '/${uri.host}$pathPart';
} else {
// Standard URL (http/https) or no host
route = uri.path.isEmpty ? '/' : uri.path;
// Ensure route starts with /
if (!route.startsWith('/')) {
route = '/$route';
}
}
// Extract query parameters
final queryParams = <String, dynamic>{};
uri.queryParameters.forEach((key, value) {
queryParams[key] = value;
});
return DeepLinkResult(route: route, queryParams: queryParams);
}