t0m3k
t0m3k

Reputation: 317

Failed assertion: 'latitude != null': is not true. I've tried several things

Error:

location.dart failed assertion: .... 'latitude != null': is not true.

Apparently, the answer is here: Flutter - Google Maps doesn´t wait to Location

However, none of these things worked for me.

Attempt:

show an empty Container() while lat and lng is null...

I have no clue what on earth this is... ==?? like with python?

lat == null || lng == null ? Container()

My guess is this guy wants me to assign lat and lng to null and put google map into a container. Here goes nothing:

var lat = null;
var lng = null;

I converted my sizedbox to a container and changed the initial camera position:

before:

SizedBox(
          height: 350,
          child: GoogleMap(
            markers: Set.from(markers),
              initialCameraPosition: _myLocation,
              myLocationEnabled: true,
              compassEnabled: true,
              myLocationButtonEnabled: true,
              mapType: MapType.normal,
              onMapCreated: (GoogleMapController controller) {
                controller.setMapStyle(Utils.mapStyles);
              }),

after:

Container(
          height: 350,
          child: GoogleMap(
            markers: Set.from(markers),
            initialCameraPosition: CameraPosition(
                target: LatLng(lat, lng),
                zoom: 15.0),
              myLocationEnabled: true,
              compassEnabled: true,
              myLocationButtonEnabled: true,
              mapType: MapType.normal,
              onMapCreated: (GoogleMapController controller) {
                controller.setMapStyle(Utils.mapStyles);
              }),
        ),

Result:

Failed assertion: 'latitude != null': is not true.

The program won't even compile now. to poke a bit, I changed the target to: target: LatLng(null, null),

Same error. Nothing has changed.

<wiped everything, started over>

"you can display a loader until you get your location"

Didn't work.

This is how I'm calling my longitude and latitude points from Google sheets. I'm trying to plot them on buttonpress:

  Future<void> _plotCurrent() async {
    Map<double,double> m = (await sheet.values.map.column(3, fromRow:2)).map((key, value)=>
        MapEntry(double.parse(key), double.parse(value)));
    Map<double,double> m2 = (await sheet.values.map.column(4, fromRow:2)).map((key, value)=>
        MapEntry(double.parse(key), double.parse(value)));


    Iterable _markers = Iterable.generate(10, (index) {
      LatLng latLngMarker = LatLng(m["test$index"], m2["test$index"]);
      return Marker(markerId: MarkerId("test$index"),position: latLngMarker);


    });

    setState(() {
      markers = _markers;
    });
  }

I've read some stuff about having to change my Widget build tree into a Future type. However, I'm still terrible with Dart. I don't know to do it. Could this work? Here's the start of my Widget:

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: Text(widget.title, style: TextStyle(fontSize: 11)),
        centerTitle: true,
      ),
      body:

      Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Form(
                key: _formKey,
                child: Padding(
                  padding: EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      TextFormField(

Please help. Thank you.

Edit:

This makes no sense.. Is geolocator messing this up or something? Here's what I have now:

  @override
  initState() {
    super.initState();
    getLocation();
  }
  var lng, lat;
  Future getLocation() async {
    Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    setState(() {
      lat = position.latitude;
      lng = position.longitude;
      print(lng);
    });
  }




  @override
  Widget build(BuildContext context) {
    if (lat == null || lng == null) {
      return Container();
    }
    Container(
      height: 350,
      child: GoogleMap(
          markers: Set.from(markers),
          initialCameraPosition: CameraPosition(
              target: LatLng(lat, lng),
              zoom: 15.0),
          myLocationEnabled: true,
          compassEnabled: true,
          myLocationButtonEnabled: true,
          mapType: MapType.normal,
          onMapCreated: (GoogleMapController controller) {
            controller.setMapStyle(Utils.mapStyles);
          }),
    );
    return Scaffold(
      key: _scaffoldKey,
      resizeToAvoidBottomPadding: false,
      appBar: AppBar(
        title: Text(widget.title, style: TextStyle(fontSize: 11)),
        centerTitle: true,
      ),
      body:

      Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Form(
                key: _formKey,
                child: Padding(

first problem is, my map isn't showing up anymore. I can print coordinates... So, I don't get why the error is still showing and everything is crashing after I press plot. Anybody?

Edit 2:

This may have something to do with my error:

The relevant error-causing widget was: MyHomePage file:///C:/Users/xxx/Desktop/xxxxx/xxxx-xxx/lib/main.dart:92:13 When the exception was thrown, this was the stack:

points to this widget:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'xx',
      theme: ThemeData(
        primarySwatch: colorCustom,
        hintColor: Colors.white,
        canvasColor: colorCustom,
        backgroundColor: Colors.red,
      ),
      home: MyHomePage(title: 'xx'),
    );
  }
}

I don't have enough experience with Dart to know what's wrong with having a homepage with a title separate from the rest of my widgets. Is this a bad thing?

I moved my widget elsewhere and applied the container. My app won't start with the lat == null || lng == null statement and throws the following error:

The following assertion was thrown building GoogleMap(state: _GoogleMapState#81111): No Directionality widget found.

I think the problem is I have too much garbage loading in. I'm lost.

    void main() => runApp(
          RestartWidget(child: MyApp()),
        );
    
    class RestartWidget extends StatefulWidget {
      RestartWidget({this.child});
    
      final Widget child;
    
      static void restartApp(BuildContext context) {
        context.findAncestorStateOfType<_RestartWidgetState>().restartApp();
      }
    
      @override
      _RestartWidgetState createState() => _RestartWidgetState();
    }
    
    class _RestartWidgetState extends State<RestartWidget> {
      Key key = UniqueKey();
    
      void restartApp() {
        setState(() {
          key = UniqueKey();
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return KeyedSubtree(
          key: key,
          child: widget.child,
        );
      }
    }



class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'xxxxxxx',
      theme: ThemeData(
        primarySwatch: colorCustom,
        hintColor: Colors.white,
        canvasColor: colorCustom,
        backgroundColor: Colors.red,
      ),
      home: MyHomePage(title: 'xxxxxxx'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();

}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  final _scaffoldKey = GlobalKey<ScaffoldState>();


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,

etc... I'm so lost in all of these Widgets. Something is causing my location to be null. I don't know. Anybody?

Upvotes: 0

Views: 1673

Answers (2)

t0m3k
t0m3k

Reputation: 317

I don't have an approximate answer. However, I do believe I found the cause of this.

Map<double, double> m = (await sheet.values.map.column(3, fromRow: 2)).map((
    key, value) =>
    MapEntry(double.parse(key), double.parse(value)));
Map<double, double> m2 = (await sheet.values.map.column(4, fromRow: 2))
    .map((key, value) =>
    MapEntry(double.parse(key), double.parse(value)));

print(_markers);

setState(() {

  Iterable _markers = Iterable.generate(10, (index) {
    LatLng latLngMarker = LatLng(m["test$index"], m2["test$index"]);
    return Marker(markerId: MarkerId("test$index"), position: latLngMarker);
  });

  markers = _markers;

In short, I'm calling the lat and long improperly somehow and it's throwing the error. I verified this by plotting a single point from my current location. Doing so worked without any issues. I'll have to research how to call my columns (coordinates) properly. If anyone has any insight, please let me know. Thanks

Edit: I think I found the problem.

my m and m2 are printing keys and values...!! The keys are messing everything up.

Upvotes: 0

Aleksandar
Aleksandar

Reputation: 1588

When dealing with async data loading, you need to have a placeholder container until your data gets loaded. In this case that's lat and long parameters.

Widget methodReturningWidget() {
    // In case your data is not ready, return empty container
    if (lat == null || long == null) {
      return Container();
    }
    // In case your data is present, return GoogleMap object
    return Container(
      height: 350,
      child: GoogleMap(
        markers: Set.from(markers),
        initialCameraPosition: CameraPosition(
            target: LatLng(lat, long),
            zoom: 15.0),
          myLocationEnabled: true,
          compassEnabled: true,
          myLocationButtonEnabled: true,
          mapType: MapType.normal,
          onMapCreated: (GoogleMapController controller) {
            controller.setMapStyle(Utils.mapStyles);
          }),
    );
}

Part of the code that is crashing your app is this here LatLng(lat, long) that tries to create object, but it's parameters lat and long are null.

Upvotes: 1

Related Questions