【问题标题】:Marker with Textinput in FlutterFlutter 中带有文本输入的标记
【发布时间】:2020-08-31 00:29:39
【问题描述】:

如何在 Flutter 中的 Google 地图上添加标记,用户可以在其中更改标题和 sn-p。它应该是用户输入,但我不知道该怎么做。在此代码中,用户可以通过在地图上长按来设置标记。但是 Info 小部件只是我在代码中选择的文本。 (我如何更改我的代码,让用户能够设置标记,而不是打开一个窗口并且用户能够在其中输入标题和片段。关闭窗口后,标记具有标题和片段用户。)这只是一个想法!!!

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';


GoogleMapController mapController;

class MapsDemo extends StatefulWidget {
  MapsDemo() : super();



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

class MapsDemoState extends State<MapsDemo> {
  //


  Completer<GoogleMapController> _controller = Completer();
  static const LatLng _center = const LatLng(51, 10);
  List<Marker> _markers = [];
  LatLng _lastMapPosition = _center;
  MapType _currentMapType = MapType.normal;



  void _currentLocation() async {
    final GoogleMapController controller = await _controller.future;
    LocationData currentLocation;
    var location = new Location();
    try {
      currentLocation = await location.getLocation();
    } on Exception {
      currentLocation = null;
    }

    controller.animateCamera(CameraUpdate.newCameraPosition(
      CameraPosition(
        bearing: 0,
        target: LatLng(currentLocation.latitude, currentLocation.longitude),
        zoom: 18.0,
      ),
    ));
  }

  _onMapCreated(GoogleMapController controller) {
    _controller.complete(controller);
  }

  _onCameraMove(CameraPosition position) {
    _lastMapPosition = position.target;
  }

  _onMapTypeButtonPressed() {
    setState(() {
      _currentMapType = _currentMapType == MapType.normal
          ? MapType.hybrid
          : MapType.normal;
    });
  }

  Future _addMarkerLongPressed(LatLng latlang) async {
    setState(() {
      final MarkerId markerId = MarkerId("RANDOM_ID");
      Marker marker = Marker(
        markerId: markerId,
        draggable: true,
        position: latlang, //With this parameter you automatically obtain latitude and longitude
        infoWindow: InfoWindow(
          title: 'This is a Marker',
          snippet: 'This looks good',
        ),
        icon: BitmapDescriptor.defaultMarker,
      );
      markers[markerId] = marker;

    });

    //This is optional, it will zoom when the marker has been created
    GoogleMapController controller = await _controller.future;
    controller.animateCamera(CameraUpdate.newLatLngZoom(latlang, 18.0));
  }

  Widget button(Function function, IconData icon) {
    return FloatingActionButton(
      onPressed: function,
      materialTapTargetSize: MaterialTapTargetSize.padded ,
      backgroundColor: Colors.blue,
      child: Icon(
        icon,
        size: 36.0,
      ),
    );
  }

  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
  @override
  Widget build(BuildContext context) {
    return MaterialApp(

      debugShowCheckedModeBanner: false,
      home: Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(40),

            child: AppBar(

              automaticallyImplyLeading: false,
              centerTitle: true,
              title:  Column(
                children: <Widget>[
                  const Text("Viewist", style: TextStyle(fontSize: 35.0),textAlign: TextAlign.center,),
                  const Text("", style: TextStyle(fontSize: 8.0),textAlign: TextAlign.center,),
                ],
              ),
              flexibleSpace: Container(
                decoration: BoxDecoration(
                    gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: <Color>[
                          Colors.greenAccent,
                          Colors.blueAccent
                        ])
                ),

              ),
            ),

        ),
        body:
        Stack(

            children: [Container(
              padding: new EdgeInsets.all(0.0),
                child: GoogleMap(
                  mapType: _currentMapType,
                  onMapCreated: _onMapCreated,
                  onCameraMove: _onCameraMove,
                  myLocationEnabled: true,
                  myLocationButtonEnabled: false,
                  initialCameraPosition: CameraPosition(
                    target: _center,
                    zoom: 6.0,
                  ),
                  compassEnabled: true,
                  tiltGesturesEnabled: false,
                  onLongPress: (latlang) {
                    _addMarkerLongPressed(latlang); //we will call this function when pressed on the map
                  },
                  markers: Set<Marker>.of(markers.values), //all markers are here
                ),
            ),


            Padding(

              padding: EdgeInsets.all(20.0),
              child: Align(
                alignment: Alignment.topRight,
                child: Column(
                  children: <Widget>[
                    button(_onMapTypeButtonPressed, Icons.map),
                    SizedBox(
                      height: 18.0,
                    ),
                    button(_currentLocation, Icons.location_searching),
                  ],
                ),

              ),
            ),
            ],
        ),
        drawer: Drawer(
          child: ListView(
              padding: new EdgeInsets.all(0.0),
            children: <Widget>[
              DrawerHeader(
                  decoration: BoxDecoration(
                      gradient: LinearGradient(colors: <Color>[
                        Colors.green,
                        Colors.lightBlueAccent
                      ])
                  ),
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Material(
                          borderRadius: BorderRadius.all(Radius.circular(40.0)),
                          elevation: 10,
                          child: Padding(padding: EdgeInsets.all(8.0),
                          child: Image.asset('images/a.png',width: 80,height: 80,),
                          ),
                        ),
                        Padding(padding: EdgeInsets.all(2.0), child: Text ('Viewist', style: TextStyle(color: Colors.white, fontSize: 30.0,),
                        )
                        )],
                    ),
                  )),
              CustomListTile(Icons.person, 'Profile', ()=>{}),
              CustomListTile(Icons.notifications, 'Notification', ()=>{}),
              CustomListTile(Icons.settings, 'Settings', ()=>{}),
              CustomListTile(Icons.lock, 'Log Out', ()=>{}),
            ],
          ),
        ),

      ),

    );
  }

}


  class CustomListTile extends StatelessWidget {
  IconData icon;
  String text;
  Function onTap;

  CustomListTile(this.icon,this.text,this.onTap);

    @override
    Widget build(BuildContext context) {
      // TODO: implement createState
      return Padding(
        padding: const EdgeInsets.fromLTRB(8.0, 0, 8.0, 0),
        child: Container(
          decoration: BoxDecoration(
            border: Border(bottom: BorderSide(color: Colors.grey.shade400))
          ),
          child: InkWell(
            splashColor: Colors.lightBlueAccent,
            onTap: onTap,
            child: Container(
              height: 50,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Icon(icon),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(text, style: TextStyle(
                          fontSize: 16.0
                        ),),
                      ),
                    ],
                  ),
                  Icon(Icons.arrow_right)
                ],
              ),
            ),
          ),
        ),
      );

    }


  }

【问题讨论】:

    标签: flutter marker


    【解决方案1】:

    当用户在地图上长按并要求他输入标记的标题时,您可以显示一个对话框。 收到标题后,关闭对话框并添加标记。

    这是一个例子:

    在 onTap 函数中带有 showDialog 函数的 Google 地图小部件

    GoogleMap(
      // other properties here
      markers: Set<Marker>.of(_markers),
      onTap: (point) => addMarker(point) // edited
    )
    

    带有TextField的对话框小部件,对话框关闭时返回数据

    class FormDialog extends StatefulWidget {
      FormDialog({Key key}) : super(key: key);
    
      @override
      _FormDialogState createState() => _FormDialogState();
    }
    
    class _FormDialogState extends State<FormDialog> {
      @override
      Widget build(BuildContext context) {
        return Container(
          child: TextField(
            onSubmitted: (value) => Navigator.pop(context, value),
            decoration: InputDecoration(
              hintText: 'Tape title of marker'
            ),
          ),
        );
      }
    }
    

    向小部件类添加功能

    Future<void> addMarker(LatLng point) async {
      var title = await showDialog<String>(
        barrierDismissible: true,
        context: context,
        builder: (context) => FormDialog(),
      );
      if (title != null) {
        setState(() {
          _markers.add(
            Marker(
              markerId: MarkerId('someId'),
              position: point,
              infoWindow: InfoWindow(title: title)
            )
          );
        });
      }
    }
    
    

    【讨论】:

    • 它不起作用。如果我实现代码,它会说:错误:参数类型“Future Function()”不能分配给参数类型“void Function(LatLng)”。 (argument_type_not_assignable 在 [map2] lib\homepage.dart:152)
    • 我该如何改进?
    • GoogleMap 小部件中的“onTap”函数期望接收一个不返回任何内容的简单函数,在此之前我们返回一个异步函数。我已经编辑了我的答案,请您测试一下并告诉我它是否有效。如果没有,请告诉我,我会花时间测试并纠正它。
    猜你喜欢
    • 2023-01-23
    • 2021-03-15
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多