Iterate elements in flutter map











up vote
0
down vote

favorite












Im trying to get array of elements in flutter with map package.



I read this tutorial to see how can i show more than one coordenates in flutter. This tutorial add elements manually, i need to add with api rest.



I created a foreach to retrieve all elements in array, then i add all coordinates in list. The problem: The list reset in initstate method, so i can´t take length of the list to loop for all coordenates.



This is the code:



 MapController mapController;
Map<String, LatLng> coords;
List<Marker> markers;
List<Map<String, LatLng>> listado = ;

Future<Null> fetchPost() async {
final response = await http.get(url);
final responseJson = json.decode(response.body);
for (Map user in responseJson) {
coords.putIfAbsent("Test", () => new LatLng(user['lat'], user['long']));
listado.add(coords);
// print(listado.toList());
}
}

@override
void initState() {
super.initState();
mapController = new MapController();
coords = new Map<String, LatLng>();
fetchPost();
markers = new List<Marker>();
for (int i = 0; i < listado.length; i++) {
print(listado[1].values.elementAt(i));
markers.add(new Marker(
width: 80.0,
height: 80.0,
point: listado[1].values.elementAt(i),
builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
}
}

@override
Widget build(BuildContext context) {
return new FlutterMap(
options: new MapOptions(
center: new LatLng(37.7525244, 139.1650556),
zoom: 5.0,
),
mapController: mapController,
layers: [
new TileLayerOptions(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c']),
new MarkerLayerOptions(markers: markers)
],
);
}
}

final String url =
'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates';

//STATES
class UserDetails {
final String name;
final double lat, long;

UserDetails({this.name, this.lat, this.long});

factory UserDetails.fromJson(Map<dynamic, dynamic> json) {
return new UserDetails(
name: json['name'],
lat: json['lat'],
long: json['long'],
);
}
}


So, how can i get all coordinates in list and iterate in loop?



UPDATE



I try



 void initState() {
super.initState();
mapController = new MapController();
coords = new Map<String, LatLng>();
fetchPost().then((data) {
print(data);
for (int i = 0; i < listado.length; i++) {
markers.add(new Marker(
width: 80.0,
height: 80.0,
point: coords.values.elementAt(i),
builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
}
});
}


But return 'the getter iterator was called on null'. The data has this json



 this: MapsPageState
data: null


Inside this i have listado array and coords but ¿how can i get?



UPDATE 2: SOLUTION



import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong/latlong.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:igota/screens/partials/alertmessages.dart';

class MapsPage extends StatefulWidget {
static String tag = 'maps-page';

@override
MapsPageState createState() => new MapsPageState();
}

class MapsPageState extends State<MapsPage> {
MapController mapController;
Map<String, LatLng> coords;
List<Marker> markers;
List<Map<String, LatLng>> list = ;
int _counter = 0;


bool loading;
Future<Null> fetchPost() async {
list = List();
markers = List();
mapController = new MapController();
coords = new Map<String, LatLng>();
final response = await http.get(
'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates').catchError((error) {
print(error.toString());
AlertMessages.general(context,'No ha sido posible acceder a los datos');
});
final List responseJson = json.decode(response.body) as List;
for (Map<String, dynamic> data in responseJson) {
_counter++;

coords.putIfAbsent("Test $_counter", () => new LatLng(double.parse(data['lat'].toString()), double.parse(data['long'].toString())));
list.add(coords);
loading=false;
}
return;
}
@override
void initState(){
loading = true;
super.initState();

fetchPost().then((data) {
for (int i = 0; i < list.length; i++) {
markers.add(new Marker(
width: 80.0,
height: 80.0,
point: list[0].values.elementAt(i),
builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
}
setState( () { } );
}).catchError((error) {
print(error.toString());
AlertMessages.general(context, 'Problemas internos de código');
});
}

@override
Widget build(BuildContext context) {
if (loading) {
return new Container(
color: Colors.red[300],
child: new Center(
child: new CircularProgressIndicator(
valueColor: new AlwaysStoppedAnimation<Color>(Colors.white),
),
));
} else {
return new FlutterMap(
options: new MapOptions(
center: new LatLng(37.7525244, 139.1650556),
zoom: 5.0,
),
mapController: mapController,
layers: [
new TileLayerOptions(
urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
subdomains: ['a', 'b', 'c']),
new MarkerLayerOptions(markers: markers)
],
);
}
}
}









share|improve this question




























    up vote
    0
    down vote

    favorite












    Im trying to get array of elements in flutter with map package.



    I read this tutorial to see how can i show more than one coordenates in flutter. This tutorial add elements manually, i need to add with api rest.



    I created a foreach to retrieve all elements in array, then i add all coordinates in list. The problem: The list reset in initstate method, so i can´t take length of the list to loop for all coordenates.



    This is the code:



     MapController mapController;
    Map<String, LatLng> coords;
    List<Marker> markers;
    List<Map<String, LatLng>> listado = ;

    Future<Null> fetchPost() async {
    final response = await http.get(url);
    final responseJson = json.decode(response.body);
    for (Map user in responseJson) {
    coords.putIfAbsent("Test", () => new LatLng(user['lat'], user['long']));
    listado.add(coords);
    // print(listado.toList());
    }
    }

    @override
    void initState() {
    super.initState();
    mapController = new MapController();
    coords = new Map<String, LatLng>();
    fetchPost();
    markers = new List<Marker>();
    for (int i = 0; i < listado.length; i++) {
    print(listado[1].values.elementAt(i));
    markers.add(new Marker(
    width: 80.0,
    height: 80.0,
    point: listado[1].values.elementAt(i),
    builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
    }
    }

    @override
    Widget build(BuildContext context) {
    return new FlutterMap(
    options: new MapOptions(
    center: new LatLng(37.7525244, 139.1650556),
    zoom: 5.0,
    ),
    mapController: mapController,
    layers: [
    new TileLayerOptions(
    urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    subdomains: ['a', 'b', 'c']),
    new MarkerLayerOptions(markers: markers)
    ],
    );
    }
    }

    final String url =
    'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates';

    //STATES
    class UserDetails {
    final String name;
    final double lat, long;

    UserDetails({this.name, this.lat, this.long});

    factory UserDetails.fromJson(Map<dynamic, dynamic> json) {
    return new UserDetails(
    name: json['name'],
    lat: json['lat'],
    long: json['long'],
    );
    }
    }


    So, how can i get all coordinates in list and iterate in loop?



    UPDATE



    I try



     void initState() {
    super.initState();
    mapController = new MapController();
    coords = new Map<String, LatLng>();
    fetchPost().then((data) {
    print(data);
    for (int i = 0; i < listado.length; i++) {
    markers.add(new Marker(
    width: 80.0,
    height: 80.0,
    point: coords.values.elementAt(i),
    builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
    }
    });
    }


    But return 'the getter iterator was called on null'. The data has this json



     this: MapsPageState
    data: null


    Inside this i have listado array and coords but ¿how can i get?



    UPDATE 2: SOLUTION



    import 'package:flutter/material.dart';
    import 'package:flutter_map/flutter_map.dart';
    import 'package:latlong/latlong.dart';
    import 'dart:convert';
    import 'package:http/http.dart' as http;
    import 'package:igota/screens/partials/alertmessages.dart';

    class MapsPage extends StatefulWidget {
    static String tag = 'maps-page';

    @override
    MapsPageState createState() => new MapsPageState();
    }

    class MapsPageState extends State<MapsPage> {
    MapController mapController;
    Map<String, LatLng> coords;
    List<Marker> markers;
    List<Map<String, LatLng>> list = ;
    int _counter = 0;


    bool loading;
    Future<Null> fetchPost() async {
    list = List();
    markers = List();
    mapController = new MapController();
    coords = new Map<String, LatLng>();
    final response = await http.get(
    'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates').catchError((error) {
    print(error.toString());
    AlertMessages.general(context,'No ha sido posible acceder a los datos');
    });
    final List responseJson = json.decode(response.body) as List;
    for (Map<String, dynamic> data in responseJson) {
    _counter++;

    coords.putIfAbsent("Test $_counter", () => new LatLng(double.parse(data['lat'].toString()), double.parse(data['long'].toString())));
    list.add(coords);
    loading=false;
    }
    return;
    }
    @override
    void initState(){
    loading = true;
    super.initState();

    fetchPost().then((data) {
    for (int i = 0; i < list.length; i++) {
    markers.add(new Marker(
    width: 80.0,
    height: 80.0,
    point: list[0].values.elementAt(i),
    builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
    }
    setState( () { } );
    }).catchError((error) {
    print(error.toString());
    AlertMessages.general(context, 'Problemas internos de código');
    });
    }

    @override
    Widget build(BuildContext context) {
    if (loading) {
    return new Container(
    color: Colors.red[300],
    child: new Center(
    child: new CircularProgressIndicator(
    valueColor: new AlwaysStoppedAnimation<Color>(Colors.white),
    ),
    ));
    } else {
    return new FlutterMap(
    options: new MapOptions(
    center: new LatLng(37.7525244, 139.1650556),
    zoom: 5.0,
    ),
    mapController: mapController,
    layers: [
    new TileLayerOptions(
    urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    subdomains: ['a', 'b', 'c']),
    new MarkerLayerOptions(markers: markers)
    ],
    );
    }
    }
    }









    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      Im trying to get array of elements in flutter with map package.



      I read this tutorial to see how can i show more than one coordenates in flutter. This tutorial add elements manually, i need to add with api rest.



      I created a foreach to retrieve all elements in array, then i add all coordinates in list. The problem: The list reset in initstate method, so i can´t take length of the list to loop for all coordenates.



      This is the code:



       MapController mapController;
      Map<String, LatLng> coords;
      List<Marker> markers;
      List<Map<String, LatLng>> listado = ;

      Future<Null> fetchPost() async {
      final response = await http.get(url);
      final responseJson = json.decode(response.body);
      for (Map user in responseJson) {
      coords.putIfAbsent("Test", () => new LatLng(user['lat'], user['long']));
      listado.add(coords);
      // print(listado.toList());
      }
      }

      @override
      void initState() {
      super.initState();
      mapController = new MapController();
      coords = new Map<String, LatLng>();
      fetchPost();
      markers = new List<Marker>();
      for (int i = 0; i < listado.length; i++) {
      print(listado[1].values.elementAt(i));
      markers.add(new Marker(
      width: 80.0,
      height: 80.0,
      point: listado[1].values.elementAt(i),
      builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
      }
      }

      @override
      Widget build(BuildContext context) {
      return new FlutterMap(
      options: new MapOptions(
      center: new LatLng(37.7525244, 139.1650556),
      zoom: 5.0,
      ),
      mapController: mapController,
      layers: [
      new TileLayerOptions(
      urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
      subdomains: ['a', 'b', 'c']),
      new MarkerLayerOptions(markers: markers)
      ],
      );
      }
      }

      final String url =
      'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates';

      //STATES
      class UserDetails {
      final String name;
      final double lat, long;

      UserDetails({this.name, this.lat, this.long});

      factory UserDetails.fromJson(Map<dynamic, dynamic> json) {
      return new UserDetails(
      name: json['name'],
      lat: json['lat'],
      long: json['long'],
      );
      }
      }


      So, how can i get all coordinates in list and iterate in loop?



      UPDATE



      I try



       void initState() {
      super.initState();
      mapController = new MapController();
      coords = new Map<String, LatLng>();
      fetchPost().then((data) {
      print(data);
      for (int i = 0; i < listado.length; i++) {
      markers.add(new Marker(
      width: 80.0,
      height: 80.0,
      point: coords.values.elementAt(i),
      builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
      }
      });
      }


      But return 'the getter iterator was called on null'. The data has this json



       this: MapsPageState
      data: null


      Inside this i have listado array and coords but ¿how can i get?



      UPDATE 2: SOLUTION



      import 'package:flutter/material.dart';
      import 'package:flutter_map/flutter_map.dart';
      import 'package:latlong/latlong.dart';
      import 'dart:convert';
      import 'package:http/http.dart' as http;
      import 'package:igota/screens/partials/alertmessages.dart';

      class MapsPage extends StatefulWidget {
      static String tag = 'maps-page';

      @override
      MapsPageState createState() => new MapsPageState();
      }

      class MapsPageState extends State<MapsPage> {
      MapController mapController;
      Map<String, LatLng> coords;
      List<Marker> markers;
      List<Map<String, LatLng>> list = ;
      int _counter = 0;


      bool loading;
      Future<Null> fetchPost() async {
      list = List();
      markers = List();
      mapController = new MapController();
      coords = new Map<String, LatLng>();
      final response = await http.get(
      'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates').catchError((error) {
      print(error.toString());
      AlertMessages.general(context,'No ha sido posible acceder a los datos');
      });
      final List responseJson = json.decode(response.body) as List;
      for (Map<String, dynamic> data in responseJson) {
      _counter++;

      coords.putIfAbsent("Test $_counter", () => new LatLng(double.parse(data['lat'].toString()), double.parse(data['long'].toString())));
      list.add(coords);
      loading=false;
      }
      return;
      }
      @override
      void initState(){
      loading = true;
      super.initState();

      fetchPost().then((data) {
      for (int i = 0; i < list.length; i++) {
      markers.add(new Marker(
      width: 80.0,
      height: 80.0,
      point: list[0].values.elementAt(i),
      builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
      }
      setState( () { } );
      }).catchError((error) {
      print(error.toString());
      AlertMessages.general(context, 'Problemas internos de código');
      });
      }

      @override
      Widget build(BuildContext context) {
      if (loading) {
      return new Container(
      color: Colors.red[300],
      child: new Center(
      child: new CircularProgressIndicator(
      valueColor: new AlwaysStoppedAnimation<Color>(Colors.white),
      ),
      ));
      } else {
      return new FlutterMap(
      options: new MapOptions(
      center: new LatLng(37.7525244, 139.1650556),
      zoom: 5.0,
      ),
      mapController: mapController,
      layers: [
      new TileLayerOptions(
      urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
      subdomains: ['a', 'b', 'c']),
      new MarkerLayerOptions(markers: markers)
      ],
      );
      }
      }
      }









      share|improve this question















      Im trying to get array of elements in flutter with map package.



      I read this tutorial to see how can i show more than one coordenates in flutter. This tutorial add elements manually, i need to add with api rest.



      I created a foreach to retrieve all elements in array, then i add all coordinates in list. The problem: The list reset in initstate method, so i can´t take length of the list to loop for all coordenates.



      This is the code:



       MapController mapController;
      Map<String, LatLng> coords;
      List<Marker> markers;
      List<Map<String, LatLng>> listado = ;

      Future<Null> fetchPost() async {
      final response = await http.get(url);
      final responseJson = json.decode(response.body);
      for (Map user in responseJson) {
      coords.putIfAbsent("Test", () => new LatLng(user['lat'], user['long']));
      listado.add(coords);
      // print(listado.toList());
      }
      }

      @override
      void initState() {
      super.initState();
      mapController = new MapController();
      coords = new Map<String, LatLng>();
      fetchPost();
      markers = new List<Marker>();
      for (int i = 0; i < listado.length; i++) {
      print(listado[1].values.elementAt(i));
      markers.add(new Marker(
      width: 80.0,
      height: 80.0,
      point: listado[1].values.elementAt(i),
      builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
      }
      }

      @override
      Widget build(BuildContext context) {
      return new FlutterMap(
      options: new MapOptions(
      center: new LatLng(37.7525244, 139.1650556),
      zoom: 5.0,
      ),
      mapController: mapController,
      layers: [
      new TileLayerOptions(
      urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
      subdomains: ['a', 'b', 'c']),
      new MarkerLayerOptions(markers: markers)
      ],
      );
      }
      }

      final String url =
      'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates';

      //STATES
      class UserDetails {
      final String name;
      final double lat, long;

      UserDetails({this.name, this.lat, this.long});

      factory UserDetails.fromJson(Map<dynamic, dynamic> json) {
      return new UserDetails(
      name: json['name'],
      lat: json['lat'],
      long: json['long'],
      );
      }
      }


      So, how can i get all coordinates in list and iterate in loop?



      UPDATE



      I try



       void initState() {
      super.initState();
      mapController = new MapController();
      coords = new Map<String, LatLng>();
      fetchPost().then((data) {
      print(data);
      for (int i = 0; i < listado.length; i++) {
      markers.add(new Marker(
      width: 80.0,
      height: 80.0,
      point: coords.values.elementAt(i),
      builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
      }
      });
      }


      But return 'the getter iterator was called on null'. The data has this json



       this: MapsPageState
      data: null


      Inside this i have listado array and coords but ¿how can i get?



      UPDATE 2: SOLUTION



      import 'package:flutter/material.dart';
      import 'package:flutter_map/flutter_map.dart';
      import 'package:latlong/latlong.dart';
      import 'dart:convert';
      import 'package:http/http.dart' as http;
      import 'package:igota/screens/partials/alertmessages.dart';

      class MapsPage extends StatefulWidget {
      static String tag = 'maps-page';

      @override
      MapsPageState createState() => new MapsPageState();
      }

      class MapsPageState extends State<MapsPage> {
      MapController mapController;
      Map<String, LatLng> coords;
      List<Marker> markers;
      List<Map<String, LatLng>> list = ;
      int _counter = 0;


      bool loading;
      Future<Null> fetchPost() async {
      list = List();
      markers = List();
      mapController = new MapController();
      coords = new Map<String, LatLng>();
      final response = await http.get(
      'https://my-json-server.typicode.com/tobiobi/myjasonserver/coordinates').catchError((error) {
      print(error.toString());
      AlertMessages.general(context,'No ha sido posible acceder a los datos');
      });
      final List responseJson = json.decode(response.body) as List;
      for (Map<String, dynamic> data in responseJson) {
      _counter++;

      coords.putIfAbsent("Test $_counter", () => new LatLng(double.parse(data['lat'].toString()), double.parse(data['long'].toString())));
      list.add(coords);
      loading=false;
      }
      return;
      }
      @override
      void initState(){
      loading = true;
      super.initState();

      fetchPost().then((data) {
      for (int i = 0; i < list.length; i++) {
      markers.add(new Marker(
      width: 80.0,
      height: 80.0,
      point: list[0].values.elementAt(i),
      builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])));
      }
      setState( () { } );
      }).catchError((error) {
      print(error.toString());
      AlertMessages.general(context, 'Problemas internos de código');
      });
      }

      @override
      Widget build(BuildContext context) {
      if (loading) {
      return new Container(
      color: Colors.red[300],
      child: new Center(
      child: new CircularProgressIndicator(
      valueColor: new AlwaysStoppedAnimation<Color>(Colors.white),
      ),
      ));
      } else {
      return new FlutterMap(
      options: new MapOptions(
      center: new LatLng(37.7525244, 139.1650556),
      zoom: 5.0,
      ),
      mapController: mapController,
      layers: [
      new TileLayerOptions(
      urlTemplate: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
      subdomains: ['a', 'b', 'c']),
      new MarkerLayerOptions(markers: markers)
      ],
      );
      }
      }
      }






      dart flutter maps






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 at 16:09

























      asked Nov 19 at 17:08









      El Hombre Sin Nombre

      185214




      185214
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote













          So the main reason listado.length is zero when you try to iterate through it is because you didn't wait for fetchPost(); method to finish its execution. You declared fetchPost(); as a future which means it runs asynchronously.



          What you need to do to ensure that by the time you attempt to iterate through listado is to perform the iteration in a call back method on the fetchPost(). So your code should look something like this:



          fetchPost().then( (data){
          for (int i = 0; i < listado.length; i++) {
          print(listado[1].values.elementAt(i));
          markers.add(new Marker(
          width: 80.0,
          height: 80.0,
          point: listado[1].values.elementAt(i),
          builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])
          ));
          }
          });


          This way, once fetchPost() completes, the callback method will be run and `listado' will have the latest data.



          I'd advise you to also introduce a isLoadingData state which you set to true whenever you call fetchPost() and to false at the end of the callback method. Just so you can let the user know that you performing some kind of processing in the background and they don't have to stare at a blank page without any feedback on what's happening.



          Hope this helps.






          share|improve this answer





















          • I try your code but return 'the getter iterator was called on null'. I think is a for problem, maybe listado.length is not correct.I updated question.
            – El Hombre Sin Nombre
            Nov 20 at 8:55


















          up vote
          0
          down vote













          Use the answer from @user8518697 and then do the following.



          -initialize markers as List<Marker> markers = new List();

          -use for(int i = 0; i < (responseJson.length); i++) instead of for(Map user in responseJson)


          I also want to say thanks for your code. I have been able to use it to display multiple markers stored in a database.






          share|improve this answer























          • I found solution. I update question.
            – El Hombre Sin Nombre
            Nov 21 at 16:10











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53379541%2fiterate-elements-in-flutter-map%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          1
          down vote













          So the main reason listado.length is zero when you try to iterate through it is because you didn't wait for fetchPost(); method to finish its execution. You declared fetchPost(); as a future which means it runs asynchronously.



          What you need to do to ensure that by the time you attempt to iterate through listado is to perform the iteration in a call back method on the fetchPost(). So your code should look something like this:



          fetchPost().then( (data){
          for (int i = 0; i < listado.length; i++) {
          print(listado[1].values.elementAt(i));
          markers.add(new Marker(
          width: 80.0,
          height: 80.0,
          point: listado[1].values.elementAt(i),
          builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])
          ));
          }
          });


          This way, once fetchPost() completes, the callback method will be run and `listado' will have the latest data.



          I'd advise you to also introduce a isLoadingData state which you set to true whenever you call fetchPost() and to false at the end of the callback method. Just so you can let the user know that you performing some kind of processing in the background and they don't have to stare at a blank page without any feedback on what's happening.



          Hope this helps.






          share|improve this answer





















          • I try your code but return 'the getter iterator was called on null'. I think is a for problem, maybe listado.length is not correct.I updated question.
            – El Hombre Sin Nombre
            Nov 20 at 8:55















          up vote
          1
          down vote













          So the main reason listado.length is zero when you try to iterate through it is because you didn't wait for fetchPost(); method to finish its execution. You declared fetchPost(); as a future which means it runs asynchronously.



          What you need to do to ensure that by the time you attempt to iterate through listado is to perform the iteration in a call back method on the fetchPost(). So your code should look something like this:



          fetchPost().then( (data){
          for (int i = 0; i < listado.length; i++) {
          print(listado[1].values.elementAt(i));
          markers.add(new Marker(
          width: 80.0,
          height: 80.0,
          point: listado[1].values.elementAt(i),
          builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])
          ));
          }
          });


          This way, once fetchPost() completes, the callback method will be run and `listado' will have the latest data.



          I'd advise you to also introduce a isLoadingData state which you set to true whenever you call fetchPost() and to false at the end of the callback method. Just so you can let the user know that you performing some kind of processing in the background and they don't have to stare at a blank page without any feedback on what's happening.



          Hope this helps.






          share|improve this answer





















          • I try your code but return 'the getter iterator was called on null'. I think is a for problem, maybe listado.length is not correct.I updated question.
            – El Hombre Sin Nombre
            Nov 20 at 8:55













          up vote
          1
          down vote










          up vote
          1
          down vote









          So the main reason listado.length is zero when you try to iterate through it is because you didn't wait for fetchPost(); method to finish its execution. You declared fetchPost(); as a future which means it runs asynchronously.



          What you need to do to ensure that by the time you attempt to iterate through listado is to perform the iteration in a call back method on the fetchPost(). So your code should look something like this:



          fetchPost().then( (data){
          for (int i = 0; i < listado.length; i++) {
          print(listado[1].values.elementAt(i));
          markers.add(new Marker(
          width: 80.0,
          height: 80.0,
          point: listado[1].values.elementAt(i),
          builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])
          ));
          }
          });


          This way, once fetchPost() completes, the callback method will be run and `listado' will have the latest data.



          I'd advise you to also introduce a isLoadingData state which you set to true whenever you call fetchPost() and to false at the end of the callback method. Just so you can let the user know that you performing some kind of processing in the background and they don't have to stare at a blank page without any feedback on what's happening.



          Hope this helps.






          share|improve this answer












          So the main reason listado.length is zero when you try to iterate through it is because you didn't wait for fetchPost(); method to finish its execution. You declared fetchPost(); as a future which means it runs asynchronously.



          What you need to do to ensure that by the time you attempt to iterate through listado is to perform the iteration in a call back method on the fetchPost(). So your code should look something like this:



          fetchPost().then( (data){
          for (int i = 0; i < listado.length; i++) {
          print(listado[1].values.elementAt(i));
          markers.add(new Marker(
          width: 80.0,
          height: 80.0,
          point: listado[1].values.elementAt(i),
          builder: (ctx) => new Icon(Icons.home, color: Colors.red[300])
          ));
          }
          });


          This way, once fetchPost() completes, the callback method will be run and `listado' will have the latest data.



          I'd advise you to also introduce a isLoadingData state which you set to true whenever you call fetchPost() and to false at the end of the callback method. Just so you can let the user know that you performing some kind of processing in the background and they don't have to stare at a blank page without any feedback on what's happening.



          Hope this helps.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 20 at 8:02









          Seale Rapolai

          687




          687












          • I try your code but return 'the getter iterator was called on null'. I think is a for problem, maybe listado.length is not correct.I updated question.
            – El Hombre Sin Nombre
            Nov 20 at 8:55


















          • I try your code but return 'the getter iterator was called on null'. I think is a for problem, maybe listado.length is not correct.I updated question.
            – El Hombre Sin Nombre
            Nov 20 at 8:55
















          I try your code but return 'the getter iterator was called on null'. I think is a for problem, maybe listado.length is not correct.I updated question.
          – El Hombre Sin Nombre
          Nov 20 at 8:55




          I try your code but return 'the getter iterator was called on null'. I think is a for problem, maybe listado.length is not correct.I updated question.
          – El Hombre Sin Nombre
          Nov 20 at 8:55












          up vote
          0
          down vote













          Use the answer from @user8518697 and then do the following.



          -initialize markers as List<Marker> markers = new List();

          -use for(int i = 0; i < (responseJson.length); i++) instead of for(Map user in responseJson)


          I also want to say thanks for your code. I have been able to use it to display multiple markers stored in a database.






          share|improve this answer























          • I found solution. I update question.
            – El Hombre Sin Nombre
            Nov 21 at 16:10















          up vote
          0
          down vote













          Use the answer from @user8518697 and then do the following.



          -initialize markers as List<Marker> markers = new List();

          -use for(int i = 0; i < (responseJson.length); i++) instead of for(Map user in responseJson)


          I also want to say thanks for your code. I have been able to use it to display multiple markers stored in a database.






          share|improve this answer























          • I found solution. I update question.
            – El Hombre Sin Nombre
            Nov 21 at 16:10













          up vote
          0
          down vote










          up vote
          0
          down vote









          Use the answer from @user8518697 and then do the following.



          -initialize markers as List<Marker> markers = new List();

          -use for(int i = 0; i < (responseJson.length); i++) instead of for(Map user in responseJson)


          I also want to say thanks for your code. I have been able to use it to display multiple markers stored in a database.






          share|improve this answer














          Use the answer from @user8518697 and then do the following.



          -initialize markers as List<Marker> markers = new List();

          -use for(int i = 0; i < (responseJson.length); i++) instead of for(Map user in responseJson)


          I also want to say thanks for your code. I have been able to use it to display multiple markers stored in a database.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 at 15:32

























          answered Nov 21 at 12:20









          user3827507

          213




          213












          • I found solution. I update question.
            – El Hombre Sin Nombre
            Nov 21 at 16:10


















          • I found solution. I update question.
            – El Hombre Sin Nombre
            Nov 21 at 16:10
















          I found solution. I update question.
          – El Hombre Sin Nombre
          Nov 21 at 16:10




          I found solution. I update question.
          – El Hombre Sin Nombre
          Nov 21 at 16:10


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53379541%2fiterate-elements-in-flutter-map%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

          Alcedinidae

          RAC Tourist Trophy