Дарт / Трепетание передачи координат из ListTile в карты Google на другой странице - PullRequest
0 голосов
/ 22 февраля 2019

У меня проблемы с отправкой координат из ListView (с ListTile, чтобы сделать их кликабельными) на мои карты Google.На данный момент, в качестве небольшого теста, я хочу, чтобы карта центрировалась на этом месте.

Экран «Мой список»:

class ListScreen extends StatelessWidget {
  final List<TrailModel> trails;
  ListScreen(this.trails);

  @override
  Widget build(BuildContext ctxt) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Here are your trails"),
      ),
      body: TrailList(trails),
    );
  }
}


class TrailList extends StatelessWidget {
  final List<TrailModel> trails;

  TrailList(this.trails);

  Widget build(context) {
    return ListView.builder(
      itemCount: trails.length,
      itemBuilder: (context, int index) {
        Object myText = json.encode(trails[index].trails);
        List<dynamic> myText2 = json.decode(myText);
        return ListTile(
          contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
          leading: Container(
            decoration: BoxDecoration(
              border: Border.all(color:Colors.black),
            ),
            padding: EdgeInsets.all(20.0),
            margin: EdgeInsets.all(10.0),
            child: Text(myText2[index]['name']),
          ),
          onTap: () {

            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => new MapScreen(myText2[index]['latitude'], myText2[index]['longitude']),
              ),
            );
          },
        );
      },
    );
  }
}

Экран «Моя карта»:

class MapScreen extends StatefulWidget {
  final double latitude;
  final double longitude;
  MapScreen(this.latitude, this.longitude);

  @override
  _MapScreenState createState() => _MapScreenState();
}

class _MapScreenState extends State<MapScreen> {
 GoogleMapController mapController;
 MapType _currentMapType = MapType.normal;

 //error here
 final LatLng _center = const LatLng(widget.latitude, widget.longitude);
 void _onMapCreated(GoogleMapController controller) {
   mapController = controller;
 }

 void _onMapTypeButtonPressed() {
   if (_currentMapType == MapType.normal) {
     mapController.updateMapOptions(
       GoogleMapOptions(mapType: MapType.satellite),
     );
     _currentMapType = MapType.satellite;
   } else {
     mapController.updateMapOptions(
       GoogleMapOptions(mapType: MapType.normal),
     );
     _currentMapType = MapType.normal;
   }
 }

 void _onAddMarkerButtonPressed() {
   mapController.addMarker(
     MarkerOptions(
       position: LatLng(
         mapController.cameraPosition.target.latitude,
         mapController.cameraPosition.target.longitude,
       ),
       infoWindowText: InfoWindowText('Random Place', '5 Star Rating'),
       icon: BitmapDescriptor.defaultMarker,
     ),
   );
 }

 @override
 Widget build(BuildContext context) {
   return MaterialApp(
     home: Scaffold(
       appBar: AppBar(
         title: Text("sample map"),
         backgroundColor: Colors.green[700],
       ),
       body: Stack(
         children: <Widget>[
           GoogleMap(
             onMapCreated: _onMapCreated,
             options: GoogleMapOptions(
               trackCameraPosition: true,
               cameraPosition: CameraPosition(
                 target: _center,
                 zoom: 11.0,
               ),
             ),
           ),
           Padding(
             padding: const EdgeInsets.all(16.0),
             child: Align(
               alignment: Alignment.topRight,
               child: Column(
                 children: <Widget>[
                   FloatingActionButton(
                     onPressed: _onMapTypeButtonPressed,
                     materialTapTargetSize: MaterialTapTargetSize.padded,
                     backgroundColor: Colors.green,
             heroTag: null,
                     child: const Icon(Icons.map, size: 36.0),

                   ),
                   const SizedBox(height: 16.0),
                   FloatingActionButton(
                     onPressed: _onAddMarkerButtonPressed,
                     materialTapTargetSize: MaterialTapTargetSize.padded,
                     backgroundColor: Colors.green,
             heroTag: null,
                     child: const Icon(Icons.add_location, size: 36.0),
                   ),
                 ],
               ),
             ),
           ),
         ],
       ),
     ),
   );
 }
}

Мои сообщения об ошибках: Оценка этого константного выражения вызывает исключение

Если я удалю const: в инициализаторах будет доступен только static

Моя первоначальная попытка состояла в том, чтобы просто перейти в конструктор, например:

double latitude;
  double longitude;
  _MapScreenState(this.latitude, this.longitude);
 final LatLng _center = const LatLng(latitude, longitude);

, но это дало мне эти 2 ошибки, плюс еще одну: аргументы константного создания должны быть выражениями const.

Пожалуйста, любая помощь будет принята с благодарностью.Поиск в этих сообщениях кажется слишком расплывчатым.Заранее спасибо

1 Ответ

0 голосов
/ 22 февраля 2019

Удалите ключевое слово const и инициализируйте _center переменную внутри конструктора.Вы можете сделать что-то вроде этого:

_MapScreenState() {
  _center = LatLng(widget.latitude, widget.longitude);
}

Вы можете отправить этот вопрос для более подробного объяснения того, почему это может работать.Надеюсь, это поможет!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...