Skip to content

Instantly share code, notes, and snippets.

@Cierra-Runis
Created May 10, 2023 22:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cierra-Runis/b0819fe7ab886f6a3cb9e1d102092d91 to your computer and use it in GitHub Desktop.
Save Cierra-Runis/b0819fe7ab886f6a3cb9e1d102092d91 to your computer and use it in GitHub Desktop.
tangled-rose-8335
void main() {
final templateUrl = '{host}/api/v3/{container}/{resourceId}';
final params = <String, dynamic>{
'host': 'www.api.com',
'container': 'books',
'resourceId': 10
};
print(templateUrl.asTemplate(params)); // www.api.com/api/v3/books/10
}
extension TemplateString on String {
String asTemplate(Map<String, dynamic> params) {
// check first
params.forEach((key, value) {
if (!RegExp(r'^[a-zA-Z_$][a-zA-Z0-9_$]*$').hasMatch(key)) {
throw Exception(
'check your params, which "$key" should match dart variable naming rule',
);
}
});
return replaceAllMapped(RegExp(r'{(.*?)}'), (match) {
final key = match.group(1);
final value = params[key];
if (value == null) {
throw Exception('Key "$key" not found in replace dictionary');
}
return value.toString();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment