Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: Escape dollar sign '$' character in strings

Tags:

flutter

dart

I have an issue facing me on a string in Flutter, specifically in a URL that includes '$' char.

Is there any way to escape the dollar sign $?

var url = Uri.parse('https://olinda.bcb.gov.br/olinda/servico/Expectativas/versao/v1/odata/ExpectativaMercadoMensais?$top=100&$skip=0&$orderby=Data%20desc&$format=json&$select=Indicador,DataReferencia,Mediana,baseCalculo');
like image 851
Rodrigo Mantovani Avatar asked Sep 11 '25 07:09

Rodrigo Mantovani


1 Answers

Dart has something called String Interpolation. Here's a snippet from the docs:

To put the value of an expression inside a string, use ${expression}. If the expression is an identifier, you can omit the {}.

Here are some examples of using string interpolation:

String Result
'${3 + 2}' '5'
'${"word".toUpperCase()}' 'WORD'
'$myObject' The value of myObject.toString()

In your case, the URL string contains exactly the escape symbol $ to make a String interpolation. Dart thinks all words after the $ symbol are identifiers (variables, functions etc.) but it doesn't find them defined anywhere. To fix it just do what @jamesdlin suggested: Escape the $ symbols like \$ or prefix the string with r like below:

r'https://...Mensais?$top=100&$skip=0&$orderby=...'.

like image 75
lepsch Avatar answered Sep 13 '25 20:09

lepsch