Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't use a variable outside my loop (flutter)

I have a problem with my flutter app, I’m trying to use a variable to stock the name of a market, but when I use this variable, outside my loop, it showed nothing, I don’t know why

var markets = [
       ["Marjane", "marjane-offers", 34.0590237712, -6.80169582367],
       ["Auto Hall", "autohall-offers", 34.0636,  -6.7973],
       ["Bricoma", "bricoma-offers", 34.0706, -6.7883],
 ];

for (var i = 0; i < markets.length; i++) {
              // GEOLOCATOR PACK
              double stopLatitude = double.parse("${markets[i][2]}");
              double stopLongitude = double.parse("${markets[i][3]}");

              double distanceInMeters = Geolocator.distanceBetween(startLatitude, startLongitude, stopLatitude, stopLongitude);

                      if (distanceInMeters < 1000) {

                        var nameMarket = markets[i][0];

                      }

                    }




                    return Text('Location always change: \n${data.latitude}/${data.longitude} \n\n A9RAB MAHAL LIK: $nameMarket');

(This code checks if I’m close to a store and show to me his name!)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I assume you are referring to the variable nameMarket. At the point of the return statement, the variable would not be in scope. What you can do is declare the variable like String? nameMarket before the for loop (which would be in scope of the return statement). And then assign to it like nameMarket = markets[i][0];

Actually, better yet might be to move the return statement into the if statement if you just want the first store that is close enough without checking the remaining stores.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading