skip to Main Content

I have a HomePage, from where I want to pass my coordinates:

child: FloatingActionButton(
 onPressed: () {
  Navigator.push(
   context,
   MaterialPageRoute(builder: (context) => MapScreen(historyItem.latLong)),
    );
   },
   child: Icon(Icons.place),
)

I want to pass them to my MapScreen, which is stateful. However, I want these coordinates to be an optional argument with initial values so that I can decide the behavior of MapScreen depending on my arguments passed:

class MapScreen extends StatefulWidget {
  const MapScreen({Key? key}) : super(key: key);

  final AppLatLong kPoint = const AppLatLong(lat: 0, long: 0);

  @override
  State<MapScreen> createState() => _MapScreenState();
}

How do I do that? Is it possible?

Thanks everyone in advance!

2

Answers


  1. make this Mapscreen constructor like this:

    MapScreen({super.key, this.lat = 0, this.long = 0});
    
    double lat;
    double long;
    

    and pass the parameter like this:

    child: FloatingActionButton(
    onPressed: () {
    Navigator.push(
     context,
    MaterialPageRoute(builder: (context) => MapScreen(lat:historyItem.lat,long:historyItem.long)),
    );
    },
    child: Icon(Icons.place),
    )
    

    let me know if this is working for you.

    Login or Signup to reply.
  2. class MapScreen extends StatefulWidget {
        const MapScreen({
             this.kPoint = const AppLatLong(lat: 0, long: 0),
             Key? key,
        }) : super(key: key);
    
        final AppLatLong kPoint;
    
        @override
      State<MapScreen> createState() => _MapScreenState();
    }
    

    Now your kPoint is optional, if you pass a kPoint you will have this, if not, you have your default value const AppLatLong(lat: 0, long: 0).
    My example is a named param, so you would’ve to use like this

     MaterialPageRoute(builder: (context) => MapScreen(kPoint: historyItem.latLong)),
    

    But if you want a positioned param, declare the param outside the curly braces:

    class MapScreen extends StatefulWidget {
        const MapScreen(
            this.kPoint = const AppLatLong(lat: 0, long: 0),
            { Key? key }
        ) : super(key: key);
    
        final AppLatLong kPoint;
    
        @override
        State<MapScreen> createState() => _MapScreenState();
    }
    

    MaterialPageRoute(builder: (context) => MapScreen(historyItem.latLong)),
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search