Home > Software design >  Flutter: Escape dollar sign '$' character in strings
Flutter: Escape dollar sign '$' character in strings

Time:06-16

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 desc&$format=json&$select=Indicador,DataReferencia,Mediana,baseCalculo');

CodePudding user response:

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

CodePudding user response:

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 desc&\$format=json&\$select=Indicador,DataReferencia,Mediana,baseCalculo');

Use a reverse slash to escape string

  • Related