Home > Back-end >  I have a problem No host specified in URI -flutter
I have a problem No host specified in URI -flutter

Time:07-26

I have a problem when i add String humanReadableAddress = await Assistants.searchAddressForGeographicCoOrdinates(userPosition!); in home page No host specified in URI https:maps.googleapis.com/maps/api/geocode/json?latlng=14.9930017,103.1029183&key=AIzaSyBrk5N28V3HECbPxVGyGk5bJJTcfXXRsSU)

//Assistants page

import 'package:geolocator/geolocator.dart';
import 'package:user/assistant/request_assistant.dart';
import 'package:user/global/map_key.dart';
import 'package:user/assistant/request_assistant.dart';

class Assistants {
  static Future<String> searchAddressForGeographicCoOrdinates(
      Position position) async {
    String humanReadableAddress = "";
    String apiUrl =
        "https:maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=AIzaSyBrk5N28V3HECbPxVGyGk5bJJTcfXXRsSU";
    var requestResponse = await RequsstAssistant.receiveRequet(apiUrl);
    if (requestResponse != "Failed") {
      humanReadableAddress = requestResponse["results"][0]["formatted_address"];
    }
    return humanReadableAddress;
  }
}

//RequsstAssistant page

import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';

class RequsstAssistant {
  static Future<dynamic> receiveRequet(String url) async {
    http.Response httpResponse = await http.get(Uri.parse(url));
    try {
      if (httpResponse.statusCode == 200) {
        String responseData = httpResponse.body;
        var decodeResponseData = jsonDecode(responseData);
        return decodeResponseData;
      } else {
        return "Error ";
      }
    } catch (exp) {
      return "Failed";
    }
  }
}

//home

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:user/assistant/assistant.dart';
import 'package:user/global/map_key.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import 'package:user/assistant/request_assistant.dart';

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

  @override
  State<Googlesmaps> createState() => _GooglesmapsState();
}

class _GooglesmapsState extends State<Googlesmaps> {
  final Completer<GoogleMapController> _controllerGooglemap = Completer();

  //ตัวแปรอาจมีค่าnullเพียงเพิ่ม?
  GoogleMapController? newgoogleMapController;

  //สร้างตัวแปร _kGooglePlex มาเก็บข้อมูลเพื่อน้ไปใช้งาน
  static const CameraPosition _kGooglePlex = CameraPosition(
    target: LatLng(
        14.989046334745291, 103.09993964569512), //กำหนดจุดศูนย์กลางของแผนที่
    zoom: 14.4746, //ยิ่งค่าน้อยยิ่งไกล
  );

  GlobalKey<ScaffoldState> skey = GlobalKey<ScaffoldState>();

  double searchLocation = 220;

  //ตำแหน่งปัจจุบัน
  Position? userPosition;
  var geoLocation = Geolocator();
  double bottomPaddingMap = 0;

  locateUserPosition() async {
    //เช็คว่ามีการเข้าถึงตำแหน่งหรือไม่
    bool serviceEnabled;
    LocationPermission permission;
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }
    Position currentPosition = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high); //รับค่าได้แม่นยำสูงสุด
    userPosition = currentPosition;

    LatLng latLngPosition =
        LatLng(userPosition!.latitude, userPosition!.longitude);
    CameraPosition cameraPosition =
        CameraPosition(target: latLngPosition, zoom: 14); //ตำแหน่งกล้อง
    newgoogleMapController!
        .animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
    // ignore: unused_local_variable
    String humanReadableAddress = await Assistants.searchAddressForGeographicCoOrdinates(userPosition!);
    // print("this is your Address = "   humanReadableAddress);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: skey,
        body: Stack(
          children: [
            GoogleMap(
              padding: EdgeInsets.only(bottom: bottomPaddingMap),
              mapType: MapType.normal,
              myLocationEnabled: true,
              zoomGesturesEnabled: true,
              zoomControlsEnabled: true,
              initialCameraPosition:
                  _kGooglePlex, //ดึงตัวแปรมา _kGooglePlex มาใช้
              onMapCreated: (GoogleMapController controller) {
                _controllerGooglemap.complete(controller);
                newgoogleMapController = controller;

                setState(() {
                  bottomPaddingMap = 240;
                });
                locateUserPosition();
              },
            ),

            //สร้างกล่องสำหรับใส่ข้อมูล
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: AnimatedSize(
                curve: Curves.easeIn,
                duration: Duration(microseconds: 120),
                child: Container(
                  height: searchLocation,
                  decoration: const BoxDecoration(
                      color: Colors.white70,
                      borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(20),
                        topRight: Radius.circular(20),
                      )),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 24, vertical: 18),
                    child: Column(children: [
                      //ช่องกรอกตำแหน่งปัจจุบัน
                      Row(
                        children: [
                          const Icon(
                            Icons.add_location_alt_outlined,
                            color: Colors.grey,
                          ),
                          const SizedBox(
                            width: 12,
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: const [
                              Text(
                                "ตำแหน่งปัจจุบันของคุณ",
                                style:
                                    TextStyle(color: Colors.grey, fontSize: 12),
                              )
                            ],
                          )
                        ],
                      ),

                      const SizedBox(height: 10),

                      const Divider(
                        height: 1,
                        thickness: 1,
                        color: Colors.grey,
                      ),

                      const SizedBox(height: 16),

                      //ช่องกรอกสถานที่ที่ต้องการจะไป
                      Row(
                        children: [
                          const Icon(
                            Icons.add_location_alt_outlined,
                            color: Colors.grey,
                          ),
                          const SizedBox(
                            width: 12,
                          ),
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: const [
                              Text(
                                "คุณต้องการไปที่ไหน?",
                                style:
                                    TextStyle(color: Colors.grey, fontSize: 12),
                              )
                            ],
                          )
                        ],
                      ),

                      const SizedBox(height: 10),

                      const Divider(
                        height: 1,
                        thickness: 1,
                        color: Colors.grey,
                      ),

                      const SizedBox(height: 16),

                      ElevatedButton(
                        child: Text("ยืนยัน"),
                        onPressed: () {},
                        style: ElevatedButton.styleFrom(
                            primary: Colors.black,
                            textStyle: const TextStyle(
                                fontSize: 16, fontWeight: FontWeight.bold)),
                      )
                    ]),
                  ),
                ),
              ),
            )
          ],
        ));
  }
}

CodePudding user response:

The error:

No host specified in URI

indicates that there's no host in the URL.

You're missing two forward slashes (//) in https::

Instead of:

String apiUrl =
        "https:maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=AIzaSyBrk5N28V3HECbPxVGyGk5bJJTcfXXRsSU";
    var requestResponse = await RequsstAssistant.receiveRequet(apiUrl);

should be:

String apiUrl =
    "https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&key=AIzaSyBrk5N28V3HECbPxVGyGk5bJJTcfXXRsSU";
var requestResponse = await RequsstAssistant.receiveRequet(apiUrl);
  • Related