"The operator '[]' isn't defined for the type 'Object'.Try defining the operator"

87 Views Asked by At

When trying to enter the collection I get the following problem

The operator '[]' isn't defined for the type 'Object'.Try defining the operator

I need help to solve this problem, I do not understand why the error occurs, and I have not found any page that can help me to solve this problem

// ignore_for_file: avoid_print, unnecessary_null_comparison
import 'dart:async';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart' as location;
import 'package:usrides/models/auth/auth.dart';
import 'package:usrides/models/providers/driver_provider.dart';
import 'package:usrides/models/providers/geofire_provider.dart';
import 'package:usrides/models/providers/user_provider.dart';
import 'package:usrides/screen/welcome/welcome_page.dart';

import '../user/user.dart';

class UserController {
  final user = FirebaseAuth.instance.currentUser!;
  final data = FirebaseFirestore.instance.collection("UsDriver");

  late Function refresh;
  late BuildContext context;
  late Position _position;

  late BitmapDescriptor markerDriver;

  late GeofireProvider _geofireProvider;
  late AuthProvider _authProvider;
  late UserProvider _userProvider;
  late DriverProvider _driverProvider;

  late StreamSubscription<Position> _positionStream;
  late StreamSubscription<DocumentSnapshot<Object?>> _statusSuscription;
  late StreamSubscription<DocumentSnapshot> _clientInfoSuscription;

  bool isConnect = false;
  Client? client;

  GlobalKey<ScaffoldState> key = GlobalKey<ScaffoldState>();
  final Completer<GoogleMapController> _mapController = Completer();

  Map<MarkerId, Marker> markers = <MarkerId, Marker>{};

  CameraPosition initialPosition = const CameraPosition(
    target: LatLng(28.2255258, -82.3596868),
    zoom: 16.0,
  );

  Future init(BuildContext context, Function refresh) async {
    this.context = context;
    this.refresh = refresh;
    _geofireProvider = GeofireProvider();
    _authProvider = AuthProvider();
    _userProvider = UserProvider();
    _driverProvider = DriverProvider();
    markerDriver = await createMarkerImageFromAsset('assets/icon/us_cars.png');
    checkGPS();
  }

  final LocationSettings _locationSettings = const LocationSettings(
    accuracy: LocationAccuracy.best,
    distanceFilter: 1,
  );

  void openDrawer() {
    key.currentState!.openDrawer();
  }

  void dispose() {
    _positionStream.cancel();
    _statusSuscription.cancel();
    _clientInfoSuscription.cancel();
  }

  void signOut() async {
    FirebaseAuth.instance.signOut();
    Navigator.pushNamed(context, WelcomePage.routeName);
  }

  void onMapCreated(GoogleMapController controller) {
    _mapController.complete(controller);
  }

  void updateLocation() async {
    try {
      await _determinePosition();
      _position = (await Geolocator.getLastKnownPosition())!;
      centerPosition();
      getNearbyDrivers();
    } catch (error) {
      print('Error de localizacion: $error');
    }
  }

  void getNearbyDrivers() {
    Stream<List<DocumentSnapshot>> stream = _geofireProvider.getNearbyDrivers(
        _position.latitude, _position.longitude, 15);

    stream.listen((List<DocumentSnapshot> documentList) {
      for (MarkerId m in markers.keys) {
        bool remove = true;

        for (DocumentSnapshot d in documentList) {
          if (m.value == d.id) {
            remove = false;
          }
        }
        if (remove) {
          markers.remove(m);
          refresh();
        }
      }

      for (DocumentSnapshot d in documentList) {
        GeoPoint point = d.data()!["position"]['geopoint'];
        addMarker(
          d.id,
          point.latitude,
          point.longitude,
          'Driver available ',
          '',
          markerDriver,
        );
      }

      refresh();
    });
  }

  void centerPosition() async {
    if (_position != null) {
      animateCamaraToPosition(_position.latitude, _position.longitude);
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("Activa el GPS"),
          backgroundColor: Color(0xFF36499B),
          elevation: 10,
        ),
      );
    }
  }

  void checkGPS() async {
    bool isLocationEnabled = await Geolocator.isLocationServiceEnabled();
    if (isLocationEnabled) {
      print('GPS Activo');
      updateLocation();
    } else {
      print('GPS Inactivo');
      bool locationGPS = await location.Location().requestService();
      if (locationGPS) {
        updateLocation();
        print('Ya activo el GPS');
      }
    }
  }

  Future animateCamaraToPosition(double latitude, double longitude) async {
    GoogleMapController controller = await _mapController.future;
    if (controller != null) {
      controller.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
        bearing: 0,
        target: LatLng(latitude, longitude),
        zoom: 16.0,
      )));
    }
  }

  Future<BitmapDescriptor> createMarkerImageFromAsset(String path) async {
    ImageConfiguration configuration = const ImageConfiguration();
    BitmapDescriptor bitmapDescriptor =
        await BitmapDescriptor.fromAssetImage(configuration, path);
    return bitmapDescriptor;
  }

  void addMarker(
    String markerId,
    double lat,
    double lng,
    String title,
    String content,
    BitmapDescriptor iconMarker,
  ) {
    MarkerId id = MarkerId(markerId);
    Marker marker = Marker(
      markerId: id,
      icon: iconMarker,
      position: LatLng(lat, lng),
      infoWindow: InfoWindow(title: title, snippet: content),
      draggable: false,
      zIndex: 2,
      flat: true,
      anchor: const Offset(0.5, 0.5),
      rotation: _position.heading,
    );

    markers[id] = marker;
  }

  Future<Position> _determinePosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    return await Geolocator.getCurrentPosition();
  }
}

enter image description here

I'm creating a taxi app. It's supposed to show the position of the taxi driver.

1

There are 1 best solutions below

2
La Pyae On

Remove parentheses from the DocumentSnapshot. And iterate the loop of data.

      for (DocumentSnapshot d in documentList) {
        final point = d.data!; /// Here you should fix
        addMarker(
          d.id,
          point.latitude,
          point.longitude,
          'Driver available ',
          '',
          markerDriver,
        );
      }