type 'Future<Dynamic>' is not a subtype of type 'Set<Marker>'

Asked

Viewed 36 times

0

Basically this code searches for the delivery locations already inserted in the databank and adds a marker on the map for them, in addition to showing the real-time position of the user. The error must be in the function loadDestinos()

import 'dart:async';
import 'package:cargas_app/controllers/destinos_controller.dart';
import 'package:cargas_app/database/sqlite/connection.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geopoint/geopoint.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sqflite/sqflite.dart';

class Entregas extends StatefulWidget {
  const Entregas({Key? key}) : super(key: key);

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

class _EntregasState extends State<Entregas> {
  String? lat = "";
  String? long = "";

  final latitude = 0.0.obs;
  final longitude = 0.0.obs;

  StreamSubscription<Position>? positionStream;
  LatLng _position = LatLng(-24.5557105, -54.0370869);
  GoogleMapController? _mapsController; //contrller for Google map
  final Set<Marker> markers = new Set(); //markers for google map
  static const LatLng showLocation =
      const LatLng(-24.5654617, -54.0558944); //location to show in map

  static Entregas get to => Get.find<Entregas>();
  get mapsController => _mapsController;
  get position => _position;

  onMapCreated(GoogleMapController gmc) async {
    _mapsController = gmc;
    watchPosicao();
    //loadDestinos();
  }

  watchPosicao() async {
    positionStream = Geolocator.getPositionStream().listen((Position position) {
      if (position != null) {
        latitude.value = position.latitude;
        longitude.value = position.longitude;
        /*_mapsController.animateCamera(
          CameraUpdate.newLatLng(
            LatLng(latitude.value, longitude.value),
          ),
        ); CENTRALIZA A CAMERA NA POSIÇÃO DO USUARIO*/
      }
    });
  }

  Future<Position> _posicaoAtual() async {
    LocationPermission permissao;
    bool ativado = await Geolocator.isLocationServiceEnabled();

    if (!ativado) {
      return Future.error('Por favor, habilite a localização no smartphone.');
    }

    permissao = await Geolocator.checkPermission();
    if (permissao == LocationPermission.denied) {
      permissao = await Geolocator.requestPermission();

      if (permissao == LocationPermission.denied) {
        return Future.error('Você precisa autorizar o acesso à localização.');
      }
    }

    if (permissao == LocationPermission.deniedForever) {
      return Future.error('Autorize o acesso à localização nas configurações.');
    }
    return await Geolocator.getCurrentPosition();
  }

  getPosicao() async {
    try {
      final posicao = await _posicaoAtual();
      latitude.value = posicao.latitude;
      longitude.value = posicao.longitude;
    } catch (e) {
      Get.snackbar(
        'Erro',
        e.toString(),
        backgroundColor: Colors.grey[900],
        colorText: Colors.white,
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }

  loadDestinos() async {
    try {
      final Database db = await Connection.get;
      List<Map<String, dynamic>> url = await db.rawQuery(
          'SELECT ds_coordenadas FROM notafiscal WHERE nr_embarque = 50729083');
      var coord = url.forEach((row) => print(row));

      List<Map<String, dynamic>> conta_notas =
          await db.rawQuery('SELECT COUNT(nr_notafiscal) FROM notafiscal');
      String cont_notas = conta_notas.toString();
      var cont = RegExp(r'(?<= )(.*)(?=})');
      var match0 = cont.firstMatch(cont_notas);
      var total_notas_string = match0!.group(0);
      var total_notas = int.parse('$total_notas_string');
      print(
          "Notas nesta ordem: $total_notas"); //mostra o total de notas nessa ordem

      for (var i = 0; i < total_notas; i++) {
        List ds_coordenadas = url;

        print("posição $i");
        String maps = ds_coordenadas[i].toString();
        // print(ds_coordenadas.toList());
        int pos_vir = maps.indexOf(","); //localiza vírgula(inutil)

        //pega a string ate a virgula
        var re = RegExp(r'(?<= )(.*)(?=,)');
        var match1 = re.firstMatch(maps);
        lat = match1!.group(0);
        var latitude = double.tryParse('$lat');

        //pega a string depois da virgula
        var re2 = RegExp(r'(?<=,)(.*)(?=})');
        var match2 = re2.firstMatch(maps);
        long = match2!.group(0);
        var longitude = double.tryParse('$long');

        final destinos = maps;

        print("Coordenadas do banco: $destinos");
        print("Posição da vírgula: $pos_vir");
        print("Latitude: $lat");
        print("Longitude: $long");

        /*return List.generate(
        maps.length,
        (i) {
          return db;
        },
      );*/

        setState(() {
          markers.add(Marker(
            //add marker manual
            markerId: MarkerId(showLocation.toString()),
            position: LatLng(latitude!, longitude!), //position of marker
            infoWindow: InfoWindow(
              //popup info
              title: 'PANIFICADORA E CONFEITARIA CANOLLIS',
              snippet: '"$i + 1" º local de entrega ',
            ),
            icon: BitmapDescriptor.defaultMarker,
          ));
        });
        return markers;
      }

      //destinos.forEach((destinos) => getmarkers(destinos));
    } catch (ex) {
      print(ex);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        brightness: Brightness.dark,
        title: Text("Roteiro"),
        backgroundColor: Color(0xffb0000CD),
      ),
      body: GoogleMap(
        zoomGesturesEnabled: true,
        initialCameraPosition: CameraPosition(
          target: showLocation, //initial position
          zoom: 10.0,
        ),
        markers: loadDestinos(),
        mapType: MapType.normal,
        onMapCreated: (controller) {
          setState(() {
            _mapsController = controller;
          });
        },
        myLocationEnabled: true,
      ),
    );
  }
}

What is returned to me:

type 'Future<dynamic>' is not a subtype of type 'Set<Marker>'
The relevant error-causing widget was
Entregas
lib\pages\Embarque.dart:46
════════════════════════════════════════════════════════════════════════════════
I/flutter (17103): {ds_coordenadas: -24.9997314,-53.4586002}
I/flutter (17103): {ds_coordenadas: -24.9690254,-53.4209546}
I/flutter (17103): {ds_coordenadas: -24.9794524,-53.4683523}
I/flutter (17103): {ds_coordenadas: -24.9535922,-53.4726166}
I/flutter (17103): {ds_coordenadas: -24.9642544,-53.4555082}
I/flutter (17103): Notas nesta ordem: 5
I/flutter (17103): posição 0
I/flutter (17103): Coordenadas do banco: {ds_coordenadas: -24.9997314,-53.4586002}
I/flutter (17103): Posição da vírgula: 28
I/flutter (17103): Latitude: -24.9997314
I/flutter (17103): Longitude: -53.4586002
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.