Untitled

mail@pastecode.io avatar
unknown
dart
2 years ago
2.5 kB
3
Indexable
Never
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:untitled1/models/robot_location.dart';

class Home extends StatefulWidget {
  final BitmapDescriptor customMarker;
  final String modelNo;

  const Home({required this.customMarker, required this.modelNo});

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

class _HomeState extends State<Home> {
  late Marker robotMarker;
  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My Robot'),
        leading: BackButton(
          onPressed: () {
            // Navigator.push(context, MaterialPageRoute(builder: (context)=>HomeScreen()));
          },
        ),
      ),
      body: StreamBuilder<DocumentSnapshot>(
        stream: FirebaseFirestore.instance
            .collection('Location')
            .doc(widget.modelNo.toString())
            .snapshots(),
        builder: (context, snapshot) {
          if (snapshot.data == null) {
            return const SizedBox();
          }
          if (!snapshot.hasData) {
            return const SizedBox();
          }
          if (snapshot.data!.data() == null) {
            return const SizedBox();
          }

          RobotLocation loc = RobotLocation.fromJson(
              snapshot.data!.data() as Map<String, dynamic>);

          LatLng robotLatLng = LatLng(loc.lat!, loc.lng!);
          chageRobotMarkerLocation(robotLatLng);
          return GoogleMap(
            initialCameraPosition:
                CameraPosition(target: robotLatLng, zoom: 17),
            onMapCreated: (GoogleMapController googleMapController) async {
              chageRobotMarkerLocation(robotLatLng);
            },
            markers: Set<Marker>.of(markers.values),
          );
        },
      ),
    );
  }

  void chageRobotMarkerLocation(LatLng locInfo) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      robotMarker = Marker(
          markerId: const MarkerId('robotLocation'),
          position: LatLng(locInfo.latitude, locInfo.longitude),
          draggable: false,
          icon: widget.customMarker);
      markers[const MarkerId('robotLocation')] = robotMarker;

      setState(() {});
    });
  }
}