Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter - if then else - variable made local only

As you can see in the code below, I want to check if a string has a ? in his name. If yes, I remove it. My problem is that the variable 'nameOfFileOnlyCleaned' stay local and is empty after the if else. Thank you for your help.

 String nameOfFile = list_attachments_Of_Reference[j].toString().split('/').last;

      if (nameOfFile.contains('?')) { //Removes everything after first '?'
        String nameOfFileOnlyCleaned = nameOfFile.substring(0, nameOfFile.indexOf('?'));
      } else{
        String nameOfFileOnlyCleaned = nameOfFile;
      }

//Here my variable 'nameOfFileOnlyCleaned' is empty. 
This is a problem because the value should be used later 
in the code. Do you know why I have this issue please? 
Many thanks.

      String extensionFile = nameOfFileOnlyCleaned.split('.').last;
      
      String url_Of_File = list_attachments_Of_Reference[j].toString();

like image 838
Laurent Thomas Avatar asked Feb 27 '26 12:02

Laurent Thomas


1 Answers

you should define your variable before if/else statement as follows:

String nameOfFileOnlyCleaned = "";
if (nameOfFile.contains('?')) { //Removes everything after first '?'
        nameOfFileOnlyCleaned = nameOfFile.substring(0, nameOfFile.indexOf('?'));
      } else{
        nameOfFileOnlyCleaned = nameOfFile;
      }

for example:

String nameOfFile = "test?test";
  String nameOfFileOnlyCleaned;
      if (nameOfFile.contains('?')) { //Removes everything after first '?'
        nameOfFileOnlyCleaned = nameOfFile.substring(0, nameOfFile.indexOf('?'));
      } else{
        nameOfFileOnlyCleaned = nameOfFile;
      }
  
  print(nameOfFileOnlyCleaned);

it returns: test as a result.

like image 89
Abbasihsn Avatar answered Mar 01 '26 13:03

Abbasihsn



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!