Home > Back-end >  I can't use a variable outside my loop (flutter)
I can't use a variable outside my loop (flutter)

Time:12-16

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!)

CodePudding user response:

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.

  • Related