如何在Flutter中将LatLng值从一个屏幕传递到下一屏幕

时间:2020-03-06 13:18:44

标签: ios flutter dart

我是新手。我试图显示谷歌地图,搜索工作正常,我可以获取经度和纬度长的值,但是我无法通过push方法将值传递给下一个视图,我尝试了以下步骤,但不起作用,请建议正确的解决方案。预先感谢。

引用:https://flutter.dev/docs/cookbook/navigation/passing-data

import 'dart:async';
import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:flutter_google_places/flutter_google_places.dart';
import 'package:google_maps_webservice/places.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
const kGoogleApiKey = "MAP_API_KEY";

class Data {
   double latitude;
   double longitude;
  Data(this.latitude, this.longitude);
}


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


GoogleMapsPlaces _places = GoogleMapsPlaces(apiKey: kGoogleApiKey);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: demo(),
      ),
    );
  }
}

class demo extends StatefulWidget {
  @override
  demoState createState() => new demoState();
}

class demoState extends State<demo> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        child: RaisedButton(
          onPressed: () async {
            // show input autocomplete with selected mode
            // then get the Prediction selected
            Prediction p = await PlacesAutocomplete.show(
                context: context, apiKey: kGoogleApiKey);
            final data = await displayPrediction(p);
            print(data.latitude); // Here, I got lat and lang value.
            Navigator.push(
          context,
          MaterialPageRoute(

            builder: (context) => _MapScreenState(data: data) //Here, I passed it.
          ),
        );

          },
          child: Text('Find address'),

        )
      )
    );
  }

  Future<Data> displayPrediction(Prediction p) async  {
    if (p != null) {
      PlacesDetailsResponse detail =
      await _places.getDetailsByPlaceId(p.placeId);

      var placeId = p.placeId;
      double lat = detail.result.geometry.location.lat;
      double lng = detail.result.geometry.location.lng;

      var address =  Geocoder.local.findAddressesFromQuery(p.description);
      print(lat);
      print(lng);
      return Data(lat, lng); 

    }
  }
}
class _MapScreenState extends StatelessWidget {

  final Data data;

  _MapScreenState({Key key, @required this.data}) : super(key: key);


    GoogleMapController myMapController;
    final Set<Marker> _markers = new Set();

    static LatLng _mainLocation =  LatLng(data.latitude,data.longitude); // Error: Only          static members can be accessed in initializers. 
    @override
    Widget build(BuildContext context) {
      return MaterialApp(
          home: Scaffold(
              appBar: AppBar(
                title: Text('Maps With Marker'),
                backgroundColor: Colors.blue[900],
              ),
              body: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Expanded(
                    child: GoogleMap(
                      initialCameraPosition: CameraPosition(
                        target: _mainLocation,
                        zoom: 10.0,
                      ),
                      markers: this.myMarker(),
                      mapType: MapType.normal,
                      onMapCreated: (controller) {
                        setState(() {
                          myMapController = controller;
                        });
                      },
                    ),
                  ),
                ],
              )));
    }

    Set<Marker> myMarker() {
      setState(() {
        _markers.add(Marker(
          // This marker id can be anything that uniquely identifies each marker.
          markerId: MarkerId(_mainLocation.toString()),
          position: _mainLocation,
          infoWindow: InfoWindow(
            title: 'Historical City',
            snippet: '5 Star Rating',
          ),
          icon: BitmapDescriptor.defaultMarker,
        ));
      });

      return _markers;
    }


  }

0 个答案:

没有答案