I am new to Flutter and generally mobile app development, so sorry if i am making any obvious mistakes . I have a Flutter_map app, and using an API to generate and draw a route with Polylines. I have a button, that when pressed, it enables to set a region to avoid during the routing. I have added a code block to add markers dynamically (second snippet), after the button is pressed, but when i do add them, the previously drawn route dissappears. Also, the lists that are used to contain the data are constantly empty. I suspect setState is responsible for this. Here is part of my code, i excluded some parts, so it can be readable.

void main() => runApp(MyApp());

List<Marker> markers = [];

class NetworkHelper {
  NetworkHelper({
      required this.startLng,
      required this.startLat,
      required this.endLng,
      required this.endLat
      });

    Future getstuff() async {

      http.Response response;

      API = response;  //pseudocode but works properly

  }
}

class MyApp extends StatelessWidget {
  //root of app
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Map',
      home: MyMap(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyMap extends StatefulWidget {
  @override
  _MyMap createState() => _MyMap();
}

class _MyMap extends State<MyMap> with SingleTickerProviderStateMixin{
  static const String route = 'map';

@override
  Widget build(BuildContext context) {

    final List<Polyline> avoids_set = [];
    final List<LatLng> polyPoints = []; 

    var data;

    double endLat = 24.8547;
    double endLng = 54.7518; 

    void getJsonData() async { 

      NetworkHelper network = NetworkHelper(
        startLat: position.latitude,
        startLng: position.longitude,
        endLat: endLat,
        endLng: endLng,
      );

      try{

        data = await network.getstuff();

        //create polylines --correct

      }catch(e){}
    }

  //---
  //update all data here

  //---

I am providing a large code block as i think i have to add alot of elements to the code in order for it to work. I also have a button to generate the route, as shown in the code

    
    return Scaffold(
      appBar: AppBar(title: Text('Map'),backgroundColor: Colors.red),
      floatingActionButton: Stack(
        fit: StackFit.expand,
        children: [

          // Route button
         Positioned(
            bottom: 20,
            right: 20,
            child: FloatingActionButton(
              onPressed: (){
                getJsonData();    
              },
              child: const Icon(Icons.navigation,size: 35),
              backgroundColor: Colors.green,
            ),  
          ),

          // button
          Positioned(
            bottom: 90,
            right: 20,
            child: FloatingActionButton(
              onPressed: button,
              child: const Icon(Icons.,size: 35),
              backgroundColor: Colors.red,
            ),
          ),

        ]
      ),
      body: 
        FlutterMap(
        options: MapOptions(
          // press for latlng points
          onLongPress: (position,latlng){    

            LatLng temp = latlng;

              Marker marker = Marker(point: latlng,
                builder: (ctx) =>
                  Container(
                    child: Icon(
                    Icons.circle_sharp,
                    size: 30,
                    color: Colors.red,
                    ),
                  ),
                );
//------------------IMPORTANT--------------------
                markers.add(marker);
                setState(() {
                  marker = marker;
              });                       
            }

          },

        layers: [
          TileLayerOptions(
              ----

          MarkerLayerOptions(
            markers:  markers,
          ),

        ],
      ), 

    );
  }

}

Basically, i need to either add the Markers dynamically, but without the setState function, or adapt the app in order for setState to work with the other functions of the app. Any help is appreciated!


Solution 1: Elvis Salabarria Aquino

what happens is that you are initializing the lists in the build so every time you call a setState it calls the build and therefore initializes the lists again declare

final List<Polyline> avoids_set = [];
final List<LatLng> polyPoints = []; 

under

static const String route = 'map';