Rodrigo Mantovani
Rodrigo Mantovani

Reputation: 61

Flutter: Escape dollar sign '$' character in strings

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');

Upvotes: 3

Views: 4098

Answers (2)

lepsch
lepsch

Reputation: 10319

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=...'.

Upvotes: 8

Kaushik Chandru
Kaushik Chandru

Reputation: 17772

Use this instead

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');

Use a reverse slash to escape string

Upvotes: 2

Related Questions