How can I have a string resource in Dart that I can refer to and replace variables in the string?
In Android, with strings.xml we can do this:
<string name="error_message">Error connecting to “%s”</string>
my_message = resources.getString(R.string.error_message, "Google")
// Error connecting to Google
In Python, we can do this:
print("I am %d years old!" % 10)
# I am 10 years old!
I want to do something like this in Dart:
var a = "My name is $s";
print(a, "Bob");
// My name is Bob
I don't want this:
var b = "World";
a = "Hello $b";
print(a)
// Hello World
The Flutter counterpart to strings.xml in Android development is the intl package. It serves the same purpose of offering an ability to internationalize apps. However, you do not have to use it for internationalization, the same way you do not have to translate strings.xml.
intlThe way you can define a message is the following:
class ParameterizedStrings {
String errorMessage(String name) => Intl.message(
'Error connecting to $name',
args: [name]);
}
You can learn more here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With