Reputation: 1212
I'm using Firebase with a Flutter application and I need to store in it the value of a String that will be interpolated based on other values from Firebase.
Record in Firebase:
{
'template': '$amount kg of $fruit',
'amount': '5',
'fruit': 'oranges'
}
What I'm doing:
String get amount => _snapshot.data()['amount'];
String get fruit => _snapshot.data()['fruit'];
Widget build(BuildContext context) {
return Text(_snapshot.data()['template']);
}
What I'm expecting: 5kg of oranges
, what Flutter renders: $amount kg of $fruit
.
How can I insert the values from amount
and fruit
in template
? The idea is that each record can configure how it will look, so another one can have $fruit: $amount kg
or any combination of amount
and fruit
Upvotes: 2
Views: 789
Reputation: 2039
String interpolation is done at compile time and so only works with constant strings. At runtime, a code cannot list variables around, so no interpolation is possible, which is good for both safety and efficiency.
As suggested by ibrahimxcool, use replaceFirst
or replaceAll
method in String
:
_snapshot.data()['template']
.replaceAll('$amount', amount)
.replaceAll('$fruit', fruit)
;
Upvotes: 1