• Uncategorized

About dart : Dart-string-interpolation-reading-a-file

Question Detail

I know that you can use the string interpolation to reference an object within a string literal but, is this possible with a string given from reading a text file?

I mean. Something like:

Function MyTemplate() {
    return (Context context) {
        return readMyFile(); // String: "My name is ${context.name}"
    }
}

I have read
Can I apply Dart’s string interpolation dynamically?

But this seems to work only with hardcoded strings.

Question Answer

String interpolation only works with hardcoded strings. You need to build your own solution or use one of the existing template packages.

A simple solution using the splitMapJoin method in the core library:

String inter(String format, Map<String, dynamic> sub ,{String placeholder = ""}){
    return format.splitMapJoin(RegExp(r'{.*?}'),
    onMatch:    (m) => sub[m.group(0).substring(1, m.group(0).length - 1)].toString() ?? placeholder,
    onNonMatch: (n) => n);
}

There is also a package to handle this.

However, these solutions are not satisfactory for my application, which also needs to interpolate a string from a file, provided by users. Since less assumptions can be made in this scenario, it is desirable that error can be detected from the input string. Thus, I developed another package to achieve this, with slight performance enhancement. This package is still in a primary stage, but all functionalities are tested. Please feedback if you have any suggestions.

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.