Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterized string variables in Dart

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
like image 802
Josh Avatar asked Oct 21 '25 12:10

Josh


1 Answers

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.

intl

The 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.

like image 73
creativecreatorormaybenot Avatar answered Oct 23 '25 03:10

creativecreatorormaybenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!