Im really new to the flutter and stuck at this point im designing the uber clone but not able to get the searched place details and also the polyline
is not coming only the progress bar
its get stuck over there only loading loading.....
E/flutter (20208): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: type 'int' is not a subtype of type 'String'
E/flutter (20208): #0 HelperMethods.getDirectionDetails (package:cab_rider/helpers/helpermethods.dart:85:22)
E/flutter (20208): <asynchronous suspension>
E/flutter (20208): #1 _MainPageState.getDirection (package:cab_rider/mainpage.dart:349:23)
E/flutter (20208): <asynchronous suspension>
E/flutter (20208): #2 _MainPageState.build.<anonymous closure> (package:cab_rider/mainpage.dart:243:29)
E/flutter (20208): <asynchronous suspension>
E/flutter (20208):
This is my HelperMethods.dart
file code :
import 'package:cab_rider/datamodels/address.dart';
import 'package:cab_rider/datamodels/directiondetails.dart';
import 'package:cab_rider/dataprovider/appdata.dart';
import 'package:cab_rider/globalvariable.dart';
import 'package:cab_rider/helpers/requesthelper.dart';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/cupertino.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:provider/provider.dart';
class HelperMethods{
static Future<String> findCordinateAddress(Position position, context) async {
String placeAddress = '';
String st1, st2, st3, st4;
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult != ConnectivityResult.mobile && connectivityResult != ConnectivityResult.wifi) {
return placeAddress;
}
String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng= ${position.latitude}, ${position.longitude}&key=$mapKey';
var response = await RequestHelper.getRequest(url);
if(response != 'failed'){
placeAddress = response['results'][0]['formatted_address'];
var placeId;
var longitude;
var latitude;
var placeFormattedAddress;
var placeName;
st1 = placeAddress = response["results"][0]["address_components"][0]["long_name"];
st2 = placeAddress = response["results"][0]["address_components"][1]["long_name"];
st3 = placeAddress = response["results"][0]["address_components"][2]["long_name"];
st4 = placeAddress = response["results"][0]["address_components"][3]["long_name"];
placeAddress = st1 ", " st2 ", " st3 ", " st4;
Address pickupAddress = new Address(placeId: placeId , longitude: longitude, latitude: latitude, placeFormattedAddress: placeFormattedAddress, placeName: placeName);
pickupAddress.longitude = position.longitude;
pickupAddress.latitude = position.latitude;
pickupAddress.placeName = placeAddress;
Provider.of<AppData>(context, listen: false).updatePickupAddress(pickupAddress);
}
return placeAddress;
}
static Future<DirectionDetails?> getDirectionDetails(LatLng startPosition, LatLng endPosition) async {
String url = 'https://maps.googleapis.com/maps/api/directions/json?origin=${startPosition.latitude},${startPosition.longitude}&destination=${endPosition.latitude},${endPosition.longitude}&mode=driving&key=$mapKey';
var response = await RequestHelper.getRequest(url); //errorline
if(response == 'failed'){
return null;
}
var durationText;
var durationValue;
var distanceText;
var distanceValue;
var encodedPoints;
DirectionDetails directionDetails = DirectionDetails(distanceText: distanceText, distanceValue: distanceValue, durationText: durationText, durationValue: durationValue, encodedPoints: encodedPoints);
directionDetails.durationText = response['routes'][0]['legs'][0]['duration']['text'];
directionDetails.durationValue = response['routes'][0]['legs'][0]['duration']['value']; //error line
directionDetails.distanceText = response['routes'][0]['legs'][0]['distance']['text'];
directionDetails.distanceValue = response['routes'][0]['legs'][0]['distance']['value'];
directionDetails.encodedPoints = response['routes'][0]['overview_polyline']['points'] ;
return directionDetails;
}
}
This is my MainPage.dart
file code: -
import 'package:cab_rider/brand_colors.dart';
import 'package:cab_rider/dataprovider/appdata.dart';
import 'package:cab_rider/helpers/helpermethods.dart';
import 'package:cab_rider/searchpage.dart';
import 'package:cab_rider/styles/styles.dart';
import 'package:cab_rider/widgets/BrandDivider.dart';
import 'package:cab_rider/widgets/ProgressDialog.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'dart:async';
import 'package:outline_material_icons/outline_material_icons.dart';
import 'dart:io';
import 'package:provider/provider.dart';
class MainPage extends StatefulWidget {
static const String id ='mainpage';
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();
double searchSheetHeight = (Platform.isIOS) ? 300 : 275 ;
Completer<GoogleMapController> _controller = Completer();
late GoogleMapController mapController;
double mapBottomPadding = 0;
var geoLocator = Geolocator();
Position? currentPosition;
void setupPositionLocator() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.bestForNavigation);
currentPosition = position;
LatLng pos = LatLng(position.latitude, position.longitude);
CameraPosition cp = new CameraPosition(target: pos, zoom: 14);
mapController.animateCamera(CameraUpdate.newCameraPosition(cp));
String address = await HelperMethods.findCordinateAddress(position, context);
print(address);
}
static final CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
);
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
drawer: Container(
width: 250,
color: Colors.white,
child: Drawer(
child: ListView(
padding: EdgeInsets.all(0),
children: <Widget>[
Container(
color: Colors.white,
height: 160,
child: DrawerHeader(
decoration: BoxDecoration(
color: Colors.white,
),
child: Row(
children: <Widget>[
Image.asset('images/user_icon.png', height: 60, width: 60,),
SizedBox(width: 15,),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Shubham',style: TextStyle(fontSize: 20, fontFamily: 'Brand-Bold'),),
SizedBox(height: 5,),
Text('View Profile'),
],
)
],
),
),
),
BrandDivider(),
SizedBox(height: 10,),
ListTile(
leading: Icon(OMIcons.cardGiftcard),
title: Text('Free Rides', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.creditCard),
title: Text('Payments', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.history),
title: Text('Ride History', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.contactSupport),
title: Text('Support', style: kDrawerItemStyle,),
),
ListTile(
leading: Icon(OMIcons.info),
title: Text('About', style: kDrawerItemStyle,),
)
],
),
),
),
body:Stack(
children: <Widget>[
GoogleMap(
padding: EdgeInsets.only(bottom: mapBottomPadding),
mapType: MapType.normal,
myLocationButtonEnabled: true,
initialCameraPosition: _kGooglePlex,
myLocationEnabled: true,
zoomGesturesEnabled: true,
zoomControlsEnabled: true,
onMapCreated: (GoogleMapController controller){
_controller.complete(controller);
mapController = controller;
setState(() {
mapBottomPadding = (Platform.isAndroid) ? 280 : 270 ;
});
setupPositionLocator();
},
),
/// MenuButton
Positioned(
top: 44,
left: 20,
child: GestureDetector(
onTap: (){
scaffoldKey.currentState!.openDrawer();
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 5.0,
spreadRadius: 0.5,
offset: Offset(
0.7,
0.7,
),
)
]
),
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 20,
child: Icon(Icons.menu, color: Colors.black87,),
),
),
),
),
/// SearchSheet
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Container(
height: searchSheetHeight,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topLeft: Radius.circular(15), topRight: Radius.circular(15)),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 15.0,
spreadRadius: 0.5,
offset: Offset(
0.7,
0.7,
)
)
]
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
SizedBox(height: 5,),
Text('Nice to see you!', style: TextStyle(fontSize: 10),),
Text('Where are you going?', style: TextStyle(fontSize: 18, fontFamily: 'Brand-Bold'),),
SizedBox(height: 20,),
GestureDetector(
onTap: () async {
var response = await Navigator.push(context, MaterialPageRoute(
builder: (context) => SearchPage()
));
if(response == 'getDirection'){
await getDirection(); // error line
}
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(4),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 5.0,
spreadRadius: 0.5,
offset: Offset(
0.7,
0.7,
)
)
]
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: <Widget>[
Icon(Icons.search, color: Colors.blueAccent,),
SizedBox(width: 10,),
Text('Search Destination'),
],
),
),
),
),
SizedBox(height: 22,),
Row(
children: <Widget>[
Icon(OMIcons.home, color: BrandColors.colorDimText,),
SizedBox(width: 12,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Add Home'),
SizedBox(height: 3,),
Text('Your residental address ',
style: TextStyle(fontSize: 11, color: BrandColors.colorDimText,),
),
]
)
],
),
SizedBox(height: 10,),
BrandDivider(),
SizedBox(height: 16,),
Row(
children: <Widget>[
Icon(OMIcons.workOutline, color: BrandColors.colorDimText,),
SizedBox(width: 12,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Add Work'),
SizedBox(height: 3,),
Text('Your Office address ',
style: TextStyle(fontSize: 11, color: BrandColors.colorDimText,),
),
]
)
],
),
],
),
),
),
)
],
)
);
}
Future<void> getDirection() async {
var pickup = Provider.of<AppData>(context, listen: false).pickupAddress;
var destination = Provider.of<AppData>(context, listen: false).destinationAddress;
var pickLatLng = LatLng(pickup!.latitude, pickup.longitude);
var destinationLatLng = LatLng(destination!.latitude, destination.longitude);
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => ProgressDialog(status: 'Please wait',)
);
var thisDetails = await HelperMethods.getDirectionDetails(pickLatLng, destinationLatLng);
Navigator.pop(context);
print(thisDetails!.encodedPoints);
}
}
#1 error points out at this line
directionDetails.durationText = response['routes'][0]['legs'][0]['duration']['text'];
directionDetails.durationValue = response['routes'][0]['legs'][0]['duration']['value']; //error line
directionDetails.distanceText = response['routes'][0]['legs'][0]['distance']['text'];
directionDetails.distanceValue = response['routes'][0]['legs'][0]['distance']['value'];
directionDetails.encodedPoints = response['routes'][0]['overview_polyline']['points'] ;
#2 error points out this line
var response = await RequestHelper.getRequest(url);
#3 error points out this line
await getDirection();
Please help me to solve this error its my final year project...
CodePudding user response:
Instead of
String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng= ${position.latitude}, ${position.longitude}&key=$mapKey';
use
String url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng= ${position.latitude.toString()}, ${position.longitude.toString()}&key=$mapKey';
and
Instead of
String url = 'https://maps.googleapis.com/maps/api/directions/json?origin=${startPosition.latitude},${startPosition.longitude}&destination=${endPosition.latitude},${endPosition.longitude}&mode=driving&key=$mapKey';
use
String url = 'https://maps.googleapis.com/maps/api/directions/json?origin=${startPosition.latitude},${startPosition.longitude}&destination=${endPosition.latitude.toString()},${endPosition.longitude.toString()}&mode=driving&key=$mapKey';
You have to convert longitude and latitude to String values using toString()
method before concatenating!
CodePudding user response:
using google_directions_api saved me while dealing with direction
CodePudding user response:
Unhandled Exception: type 'int' is not a subtype of type 'String'
It seems you declare a Variable as an Int on the server-side make that Variable as String the problem will be resolve.