Friday, October 23, 2020

How to Test Your Apps Wireless on Android Phone

 How to Test Your Flutter Apps Wireless on Android Phone



adb.exe tcpip 5555
adb.exe connect 192.168.43.1:5555
...............................................................................................................................................................................................................................
Step :#1 [Pro Level ] 
  1. Connect your device to PC by USB cable to pc(one time requirement only) .
  2. Turn on usb debugging it will connect successfully(allow for connection in device for promoted message).
  3. Then type this Command in terminal  adb.exe tcpip 5555
  4. Now remove the USB cable and it's no longer required
  5. Make sure your phone and machine is connected in the same wifi
  6. Connect device with pc with wifi now type this command  adb.exe connect <your_ip>:5555

you're all done !!
...................................................................................................................................................................................................................................
Step :#1 [Beginner Level ] 
How to Access Developer Options and Enable USB Debugging on Android

To enable Developer Options, open the Settings screen, scroll down to the bottom, and tap About phone.




Tap the Build number field seven times to enable Developer Options. Tap a few times and you’ll see a toast notification with a countdown that reads.








How to Enable USB Debugging

To enable USB Debugging,  you’ll need to jump into the Developer options menu, scroll down to the Debugging section, and toggle the USB Debugging slider.




Allow USB debugging?  Ok






Almost done here. :)

.........................................................................................................................................................................................................................
You can now connect your device with USB. You can verify that your device is connected by executing adb devices from the android_sdk/platform-tools/ directory. If connected, you'll see the device name listed as a "device."
 adb.exe devices

Just for the info, the adb help says that
1. adb.exe usb                     
 



2. Allow it 


3. adb.exe tcpip <port>         
   adb.exe tcpip 5555    

4. Now Remove the USB cable and it's no longet require

5. How to find out th IP address 
open a command prompt and type ipconfig


6. How to connect ?
adb.exe connect <ip-address>:5555


7. How to Stop or restart android adb serive from command prompt 
  adb.exe kill-server



Thursday, October 22, 2020

TextField || FLutter

 .......................................................................................................................................................................................................................................
Example : #1 [ TextField ]

Introduction to TextField
A TextField widget allows collection of information from the user. The code for a basic TextField is as simple as 

1. TextField()

2. Working with autofocus
        TextField(
          autofocus: true,
            ),

3 . Keyboard Type
        TextField(
          keyboardType: TextInputType.number,
        ),

    TextInputType.text (Normal complete keyboard)
    TextInputType.emailAddress (Normal keyboard with an “@”)

4. TextInputAction
TextField(
  textInputAction: TextInputAction.continueAction,
),
TextField(
  textInputAction: TextInputAction.send,
),
 
5. Autocorrect
TextField(
  autocorrect: false,
),

6. Text Capitalization
TextField(
  textCapitalization: TextCapitalization.sentences,
),
TextCapitalization.words
TextCapitalization.characters
TextCapitalization.sentences

7. Text alignment inside the TextField
TextField(
  textAlign: TextAlign.center,
),

8. Styling the text inside the TextField
TextField(
  style: TextStyle(color: Colors.red, fontWeight: FontWeight.w300),
),

9. Changing the cursor in the TextField
TextField(
  cursorColor: Colors.red,
  cursorRadius: Radius.circular(16.0),
  cursorWidth: 16.0,
),


10. Controlling the Size and Maximum Length in a TextField
TextField(
  maxLength: 4,
),

11. Making an expandable TextField
TextField(
  maxLines: 3,
)

12. Obscuring Text
TextField(
  obscureText: true,
),

13. Adjust the Styles
style: TextStyle(height: 2.0),     //increases the height of cursor

14. Increase the width of the Cursor:
     TextField(
         cursorWidth: 5.0,
      ),

15. Add Decorations
decoration: InputDecoration(
  hintText: "Hint text sample",
  border: OutlineInputBorder(
    borderRadius: BorderRadius.circular(5.0),
    borderSide: BorderSide(
      color: Colors.amber,
      style: BorderStyle.solid,
    ),
  ),
),

16. Enable or disable the TextField:
enabled:true,             //dafult, makes the textfield interactive
enabled:false,          //make the textfield non editable

17. Make the cursor invisible: We can make the cursor invisible with showCursor:
    showCursor: false,

18. toolbarOptions: 
Adds or removes toolbar options such as cut, copy, paste, selectAll.
toolbarOptions: ToolbarOptions(
  cut: true,
  copy: false,
  selectAll: true,
  paste: false,
),

 .......................................................................................................................................................................................................................................
Example : #2
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hello World'),
      ),
      body: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String _username, _email, _password = "";

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(30),
      child: Column(
        children: [
          UserInput(), 
          EmailInput(), 
          PasswordInput(), 
          SubmitButton()
          ],
      ),
    );
  }
}

Widget UserInput() {
  return TextFormField(
    keyboardType: TextInputType.text,
    decoration: InputDecoration(labelText: 'Enter Email'),
    textInputAction: TextInputAction.next,
  );
}

Widget EmailInput() {
  return TextFormField(
    keyboardType: TextInputType.emailAddress,
    decoration: InputDecoration(labelText: 'Enter Username'),
    textInputAction: TextInputAction.next,
  );
}

Widget PasswordInput() {
  return TextFormField(
    obscureText: true,
    keyboardType: TextInputType.text,
    decoration: InputDecoration(labelText: 'Enter Password'),
    textInputAction: TextInputAction.done,
  );
}

RaisedButton SubmitButton() {
  return RaisedButton(
    onPressed: () {},
    child: Text('Submit'),
  );
}
 .......................................................................................................................................................................................................................................
Example : #3 [ Validation ]
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  void validate() {
    if (formKey.currentState.validate()) {
      print('Successfull');
    } else {
      print('Error');
    }
  }

  String emailvalidate(value) {
    if (value.isEmpty) {
      return 'Enter Email Address';
    } else {
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Validatetor'),
      ),
      body: Padding(
        padding: EdgeInsets.all(30.0),
        child: Center(
          child: Form(
              key: formKey,
              child: Column(
                children: [
                  TextFormField(
                    decoration: InputDecoration(
                      labelText: 'Enter Email',
                      border: OutlineInputBorder(),
                    ),
                    validator: emailvalidate,
                  ),
                  Padding(
                    padding: const EdgeInsets.all(20.0),
                    child: RaisedButton(
                      child: Text('Login'),
                      onPressed: validate,
                    ),
                  )
                ],
              )),
        ),
      ),
    );
  }
}
 .......................................................................................................................................................................................................................................
Example : #4

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() {
  SystemChrome.setEnabledSystemUIOverlays([]);
  runApp(
    MyApp(),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Forms',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Forms'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  
  final TextStyle textstyle =
      TextStyle(color: Colors.white, fontWeight: FontWeight.bold);
  final InputDecoration decoration = InputDecoration(
    border: OutlineInputBorder(),
  );
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
         padding: const EdgeInsets.all(30.0),
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                FlutterLogo(
                  size: 190,
                ),
                SizedBox(
                  height: 15,
                ),
                TextFormField(
                  decoration: decoration,
                ),
                SizedBox(
                  height: 15,
                ),
                TextFormField(
                  decoration: decoration,
                ),
                SizedBox(
                  height: 15,
                ),
                MaterialButton(
                  onPressed: (){},
                  color: Colors.red,
                  minWidth: 160,
                  child: Text(
                    'Google',
                    style: textstyle,
                  ),
                ),
                MaterialButton(
                  onPressed: (){},
                  color: Colors.blue,
                  minWidth: 160,
                  child: Text(
                    'Facebook',
                    style: textstyle,
                  ),
                ),
                MaterialButton(
                  onPressed: (){},
                  color: Colors.orange,
                  minWidth: 160,
                  child: Text(
                    'E-mail',
                    style: textstyle,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
Happy Coding :)



 .......................................................................................................................................................................................................................................
Example : #4





Express Js || REST Api

 npm init 

or 
npm int -y

npm install --save express

what is nodemon 
npm install -g nodemon --save 
npm install --save-dev nodemon

I want to run nodemon server.js. 


const express = require('express');
const app =express();

const port = process.env.PORT ||5000;
app.get('/', (req, res)=>res.json('Hello World'));

app.listen(port,(req, res)=>{
console.log(`Server running on port ${port}`);
})










npm install --save mongoose




const express = require('express');
const mongoose =require('mongoose');
const app =express();

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser:true});

const connection =mongoose.connection;
connection.once("open",()=>console.log('connection successfull'));

const port = process.env.PORT ||5000;
app.get('/', (req, res)=>res.json('Hello World'));


app.listen(port,(req, res)=>{
    console.log(`Server running on port ${port}`);
})

................................................................................................................................................................................................................................
Example :#1 [Post Example ]

models/userSchema.js
const mongoose = require('mongoose');
const schema = mongoose.Schema;

const User = schema({
    username:{
        type: String,
        required:true,
        unique:true,
    },
    password:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    }
    })
    module.exports = mongoose.model("User", User);
....................................................................
routers/router.js
const express = require('express');
const router = express.Router();
const User = require('../model/userSchema');

router.route('/register').post((req, res)=>{
    console.log('inside user');
    const user = new User({
        username:req.body.username,
        password: req.body.password,
        email: req.body.email
    });
    user.save()
    .then(()=>{
        console.log('User Reegister Successfull');
        res.status(200).json('Okay');
    })
    .catch((error)=>{
        res.status(403).json({msg:error});
    });
   // res.json('Registered')
});


router.route("/:username").patch((req, res) => {
    User.findOneAndUpdate(
        { username: req.params.username },
        { $set: { password: req.body.password } },
        (err, result) => {
            if (err) return res.status(500).json({ msg: err });
            const msg = {
                msg: "password Successfuly updated",
                username: req.params.username,
            };
            return res.json(msg);
        })
})


router.route("/:username").delete((req, res) => {
    User.findOneAndDelete(
        { username: req.params.username },
        (err, result) => {
            if (err) return res.status(500).json({ msg: err });
            const msg = {
                msg: "User Deleted",
                username: req.params.username
            };
            return res.json(msg);
        }
    )
})


module.exports = router;
..............................................................
server.js
const express = require('express');
const mongoose =require('mongoose');
const app =express();
const userRouter = require('./routes/route');

mongoose.connect('mongodb://localhost:27017/myapp', {useNewUrlParser:true});

const connection =mongoose.connection;
connection.once("open",()=>console.log('connection successfull'));

const port = process.env.PORT ||5000;
app.get('/', (req, res)=>res.json('Hello World'));
app.use(express.json());
app.use('/user', userRouter);
app.listen(port,(req, res)=>{
    console.log(`Server running on port ${port}`);
})

....................................................................................................................................................................................................................................



....................................................................................................................................................................................................................................



Monday, October 19, 2020

Flutter || Common Errors

 1. How to Fix Android License Status Unknown In Flutter? 

Users can give a try to below things in a command prompt.
flutter doctor --android-licenses
and type Y when needed to accept the licenses.

Note : Try to run as administrator

 Step: #1
 If it is throwing some exceptions like 
java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema etc.


It means your java is not installed or not the correct version. move to the next step.
 Step: #1  JAVA 8.1 and JAVA_HOME path.

Install JAVA 8.1 and set the JAVA_HOME path. Make sure it is version 8.1 register a free account and download from oracle the 8.1 version, remember above 11+ won’t work for flutter

...................................................................................................................................................................................................................................
2. How to Solve No Connected Devices in Flutter?

<ANDROID_SDK_HOME>\platform-tools>adb devices
List of devices attached
4df798d76f98cf6d        unauthorized
.......................................................
Restart ADB Server:

adb kill-server
adb start-server

...................................................................................................................................................................................................................................
3. Dart DevTools?

Dart DevTools exited with code 1. Resolving dependencies... + args 1.6.0 + async 2.4.2 + browser_launcher 0.1.7 + charcode 1.1.3 + collection 1.14.13 + convert 2.1.1 + crypto 2.1.5 + devtools 0.9.3+4 + devtools_server 0.9.3+4 + devtools_shared 0.9.3+4 + http 0.12.2 + http_multi_server 2.2.0 + http_parser 3.1.4 + intl 0.16.1 + logging 0.11.4 + meta 1.2.3 + mime 0.9.7 + path 1.7.0 + pedantic 1.9.2 + shelf 0.7.9 + shelf_proxy 0.1.0+7 + shelf_static 0.2.8 + source_span 1.7.0 + sse 3.5.0 + stack_trace 1.9.5 + stream_channel 2.0.0 + string_scanner 1.0.5 + term_glyph 1.1.0 + typed_data 1.2.0 + usage 3.4.2 + uuid 2.2.2 + vm_service 5.2.0 + webkit_inspection_protocol 0.7.3 Downloading devtools 0.9.3+4... Failed to rename directory because access was denied. This may be caused by a virus scanner or having a file in the directory open in another application.

Solutions
So, please try running this from your terminal
flutter pub global activate devtools
Note : Try to run as administrator

Flutter/bin/cache/dart-sdk/bin/pub global activate devtools

in Mycase - 
C:\Users\sapan\Downloads\flutter_windows_1.22.2-stable\flutter\bin\cache\dart-sdk\bin>pub global activate devtools

https://pub.dev/packages/devtools/install
pub global activate devtools

Type chrome => http://127.0.0.1:9100/

Connecting to VM Service at 




Saturday, October 10, 2020

Flutter Google Maps | Geolocator | Geocoder

Flutter Google Maps

What you'll build
you'll build a mobile app featuring a Google Map using the Flutter SDK. Your app will:
  • Display a Google Map
  • Add a Image and Text 
  • Dispay infoworld
  • Display this data as markers as well as custom marker also on the Map,
  • polygon
  • Retrieve map data from a web service
  • Get User Address
  • Latitude to convert Address
  • Hide map api key
Important Step
Step :#1 [ Location permissions ]

Important Library
https://pub.dev/packages/google_maps_flutter
  google_maps_flutter: ^1.1.1

https://pub.dev/packages/geocoder/install
  geocoder: ^0.2.1

https://pub.dev/packages/geolocator/install
  geolocator: ^6.1.14


Official Doc
https://developers.google.com/maps/documentation/android-sdk/location

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

       android:usesCleartextTraffic="true"


Step :#2 [ change gradle.properties ]
android.enableDexingArtifactTransform=false


Step :#3 [ Add Key ]

        <meta-data android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyAIZ40uk5L-Q"/>


Step :#4 [ It's always not mandatory if sdk is 21 ]
android\app\build.gradle       

        minSdkVersion 21
        multiDexEnabled true


Step :#5 
1. If you want to test Physical device? It's mendartoy update or clear cache of Google play service.
2. Test with Emulator do Install it


Step :#6 [ Hiding API_KEY ]
First, put your key in the android/local.properties

MAPS_API_KEY= Paste here api key


In android/app/build.gradle , add this line

def localPropertyApiToken = localProperties.getProperty("MAPS_API_KEY")
def systemEnvApiToken = System.getenv('MAPS_API_KEY')
def MAPS_API_KEY = localPropertyApiToken != null ? localPropertyApiToken : systemEnvApiToken


In android/app/build.gradle , add this line

manifestPlaceholders = [MAPS_API_KEY: MAPS_API_KEY]


In android\app\src\main\AndroidManifest.xml , add this line

<meta-data android:name="com.google.android.geo.API_KEY"
    android:value="${MAPS_API_KEY}"/>





Happy Coding :)
...............................................................................................................................................................................................................................
Basic Setup for Google Maps 
Create and  setup a new Google Cloud Platform (GCP) project

1. Go to Google Cloud Platform Console. 
https://console.cloud.google.com/?pli=1



2. Go to Project Selection dialog-box and click New Project.


3. Enter the project



Enabling APIs
Now, search for Maps and enable Maps SDK for both platforms.









Same process for iOS





You will also need the Directions API while drawing the routes. So enable that as well.


Generating an API key

You will need an API key for integrating Google Maps into your app.
Go to APIs & Services from the left menu and select Credentials.

Click CREATE CREDENTIALS and select API key.



This will generate an API key for the project, you will need this in the next step.


Select Apis





Set up the Flutter project
Create a new Flutter project.

flutter create google_map_poly_distance

cd google_map_poly_distance


Setp #1 [ dependency  ]
The first step is to add the Google Maps Flutter plugin as a dependency in the pubspec.yaml file. The package is available as google_maps_flutter on pub.dartlang.org.
https://pub.dev/packages/google_maps_flutter  Once you do that, you need to run flutter packages get.

  google_maps_flutter: ^1.1.1


Setp #2 [API KEY ]
The next step is getting an API key for both Android and iOS. For Android, follow the instructions at Maps SDK for Android, Get API Key. Once you have your API key,  add it to your Flutter app in the application manifest (android/app/src/main/AndroidManifest.xml), as follows

<manifest ...
  <application ...
    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR ANDROID API KEY HERE"/>



Copy the API key paste above



iOS setup
Navigate to the file ios/Runner/AppDelegate.swift and replace the whole code with the following:

import UIKit
import Flutter
import GoogleMaps
  
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    //Add your Google Maps API Key here
   // GMSServices.provideAPIKey("AIzddR-h27Ypjn0kgYJEP6wWg")

    GMSServices.provideAPIKey("YOUR KEY HERE")
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Also, add the following to ios/Runner/Info.plist file:
<key>io.flutter.embedded_views_preview</key> 
<string>YES</string>

To get the location permission, add the following to the same file:

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>

//
<key>io.flutter.embedded_views_preview</key>
<string>YES</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>

//
Setp #3 [Adding a GoogleMap widget]
Now you are ready to add a GoogleMap widget! Run flutter clean to make sure the API key changes are picked up on the next build. Then, add a GoogleMap widget that covers the entire screen.

Setp #4 [ Code Here... ]
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
      title: Text('Flutter Google Maps'),
    ),
    body: GoogleMap(  
      initialCameraPosition: CameraPosition(  
        target: LatLng(19.043470, 72.819536),
        zoom: 14.0
      )
    ),
    );
  }
}

Basic Code

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  GoogleMapController mapController;
  CameraPosition initialLocation = CameraPosition(target: LatLng(0.0, 0.0));

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: GoogleMap(
        initialCameraPosition: initialLocation,
        myLocationEnabled: true,        //give locations circle on the right corner of top
        myLocationButtonEnabled: false,
        mapType: MapType.normal,
        zoomGesturesEnabled: true,
        zoomControlsEnabled: false,         // + or - disable button on right side bottom corner
        onMapCreated: (controller) {
          mapController = controller;
        },
      ),
    );
  }
}
Happy Coding :)
...............................................................................................................................................................................................................................
Fetching current location
There is a nice plugin for Flutter, known as geolocator that can help you to fetch user’s current location easily. Add it to your pubspec.yaml file.

https://pub.dev/packages/geolocator/install
  geolocator: ^6.1.14

Code Here
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  GoogleMapController mapController;
  CameraPosition initialLocation = CameraPosition(target: LatLng(0.0, 0.0));
  Position currentPosition;

  Future<void> getCurrentLocation() async {
    await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
        .then((Position position) async {
      setState(() {
        currentPosition = position;
        print("CURRENT POSITION: $currentPosition");


        mapController.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: LatLng(position.latitude, position.longitude),
              zoom: 18.0,
            ),
          ),
        );
      });
    }).catchError((e) {
      print(e);
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GoogleMap(
        onTap: (tapped) => ({tapped.latitude,tapped.longitude }),

        initialCameraPosition: initialLocation,
        myLocationEnabled: true,                //give locations circle on the right corner of top
        myLocationButtonEnabled: false,
        zoomControlsEnabled: false,         // or disable button on right side bottom corner
        mapType: MapType.normal,
        zoomGesturesEnabled: true,

        onMapCreated: (GoogleMapController controller) {
          mapController = controller;
        },
      ),
    );
  }
}

...............................................................................................................................................................................................................................
Drawing Route Lines on Google Maps Between Two Locations in Flutter
using Flutter Polyline Points Package

Add a dependencies 
https://pub.dev/packages/flutter_polyline_points/install

  flutter_polyline_points: ^0.2.4


Completer<GoogleMapController> _controller = Completer();
// this set will hold my markers
Set<Marker> _markers = {};

// this will hold the generated polylines
Set<Polyline> _polylines = {};

// this will hold each polyline coordinate as Lat and Lng pairs
List<LatLng> polylineCoordinates = [];

// this is the key object - the PolylinePoints
// which generates every polyline between start and finish

PolylinePoints polylinePoints = PolylinePoints();
String googleAPIKey = “<YOUR_API_KEY>”;

// for my custom icons
BitmapDescriptor sourceIcon;
BitmapDescriptor destinationIcon;





...............................................................................................................................................................................................................................
Geocoding 
Geocoding is a technique by which the address of a place can be converted to their coordinates (latitude & longitude) and vice versa.



...............................................................................................................................................................................................................................
Example :#1[ Add a Text and Image]

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}
class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: Stack(
          children: [
            GoogleMap(
                initialCameraPosition: CameraPosition(
                    target: LatLng(19.043470, 72.819536), zoom: 14.0)),
            Container(
              width: 150.0,
              height: 150.0,
              alignment: Alignment.topCenter,
              child: Image.asset('assets/images/d.jpg', ),
            ),
            Container(
              alignment: Alignment.bottomCenter,
              child: Text(
                'Flutter Google Maps',
                style: Theme.of(context).textTheme.headline3,
              ),
            )
          ],
        ));
  }
}

Happy Coding :)
...............................................................................................................................................................................................................................
Example :#2 [ Add a Marker] 

import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  var myMarkers = HashSet<Marker>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: GoogleMap(
          markers: myMarkers,
          initialCameraPosition:
          CameraPosition(target: LatLng(19.043470, 72.819536), zoom: 14.0),

          onMapCreated: (GoogleMapController googleMapController) {
            setState(() {
              myMarkers.add(Marker(
                markerId: MarkerId('1'),
                position: LatLng(19.043470, 72.819536),
              ));
            });
          },
        ));
  }
}

.......................................................
Clean Code...

import 'dart:async';
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  static const LatLng _latLng = LatLng(19.043470, 72.819536);

  var myMarkers = HashSet<Marker>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: GoogleMap(
          initialCameraPosition: CameraPosition(target: _latLng, zoom: 14.0),
          markers: myMarkers,
        ));
  }
}
..............................
Another code of marker for two destionations
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  GoogleMapController googleMapController;
  CameraPosition cp =
      CameraPosition(target: LatLng(19.053766, 72.841979), zoom: 14.000);

  final Set<Marker> marker = Set();
  final LatLng sourceLatLong = LatLng(19.053766, 72.841979);
  final LatLng destinationLatLong = LatLng(19.057342, 72.826705);

  @override
  void initState() {
    super.initState();
    marker.add(Marker(
        markerId: MarkerId("1"),
        position: sourceLatLong,
        infoWindow: InfoWindow(title: "Source Mumbai"),
        icon: BitmapDescriptor.defaultMarker,
        visible: true));

    marker.add(Marker(
      markerId: MarkerId("2"),
      position: destinationLatLong,
      infoWindow: InfoWindow(title: "BKC"),
      icon: BitmapDescriptor.defaultMarker,
      visible: true,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return GoogleMap(
      initialCameraPosition: cp,
      myLocationEnabled: true,
      mapType: MapType.normal,
      onMapCreated: (GoogleMapController controller) {
        googleMapController = controller;
      },
      markers: marker,
    );
  }
}


Happy Coding :)
...............................................................................................................................................................................................................................
Example :#3[ InfoWindow ]

import 'dart:async';
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  Completer<GoogleMapController> _controller = Completer();
  static const LatLng _latLng = LatLng(19.043470, 72.819536);

  var myMarkers = HashSet<Marker>();

  void _onMapCreated(GoogleMapController googleMapController) {
    _controller.complete(googleMapController);
    setState(() {
      myMarkers.add(Marker(
          markerId: MarkerId('1'),
          position: _latLng,
          infoWindow: InfoWindow(
              title: 'Taj Land End, Mumbai', snippet: '5 star Rating')));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: GoogleMap(
          initialCameraPosition: CameraPosition(target: _latLng, zoom: 14.0),
          markers: myMarkers,
          onMapCreated: _onMapCreated,
        ));
  }
}


Happy Coding :)
...............................................................................................................................................................................................................................
Example :#4 [ Add a Custom Marker ]

import 'dart:async';
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  Completer<GoogleMapController> _completer = Completer();
  static const LatLng _latLng = LatLng(19.077098, 72.851786);

  var myMarkers = HashSet<Marker>();

  void _onMapCreated(GoogleMapController googleMapController) async {
    _completer.complete(googleMapController);
    setState(() {
      myMarkers.add(Marker(
          markerId: MarkerId('1'), 
          position: _latLng, 
          icon: bitmapDescriptor,
          infoWindow: InfoWindow(  
            title: 'Grand Hyatt, Mumbai',
            snippet: '5 Start Rating'
          )
          ),
          );
       });
  }

  BitmapDescriptor bitmapDescriptor;
  getCustomMarker() async {
    bitmapDescriptor = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration.empty, 'assets/images/do.jpg');
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Google Maps'),
      ),
      body: GoogleMap(
        initialCameraPosition: CameraPosition(target: _latLng, zoom: 14),
        markers: myMarkers,
        onMapCreated: _onMapCreated,
      ),
    );
  }
}

Happy Coding :)
...............................................................................................................................................................................................................................
Example :#5 [ polygon ]

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
static const LatLng _latLng = LatLng(37.43296265331129, -122.08832357078792);

Set<Polygon> myPolygon() {
  var polygonCoords = List<LatLng>();    
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08332357078792));
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));

  var polygonSet = Set<Polygon>();
  polygonSet.add(
    Polygon(
      polygonId: PolygonId('1'),
      points: polygonCoords,
      strokeColor: Colors.red,
      )
      );
  return polygonSet;
}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Google Maps'),
      ),
      body: GoogleMap(
        mapType: MapType.normal,
        initialCameraPosition: CameraPosition(target: _latLng, zoom: 14),
        polygons: myPolygon(),
      ),
    );
  }
}

Happy Coding :)
...............................................................................................................................................................................................................................
Example :#6

...............................................................................................................................................................................................................................
Example :#7
import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() => runApp(MaterialApp(home: MyApp()));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
  var myMarkers = HashSet<Marker>();
  BitmapDescriptor bitmapDescriptor;
  getCustomMarker() async {
    bitmapDescriptor = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration.empty, 'assets/images/do.jpg');
  }

  @override
  void initState() {
    super.initState();
    getCustomMarker();
  }
  Set<Polygon> myPolygon() {
  var polygonCoords = List<LatLng>();    
  //polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
   polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08832357078792));
  polygonCoords.add(LatLng(37.43006265331129, -122.08332357078792));
  polygonCoords.add(LatLng(37.43296265331129, -122.08832357078792));

  var polygonSet = Set<Polygon>();
  polygonSet.add(
    Polygon(
      polygonId: PolygonId('1'),
      points: polygonCoords,
      strokeColor: Colors.red,
      )
      );
  return polygonSet;
}
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: Stack(
          children: [
            GoogleMap(
              initialCameraPosition: CameraPosition(
                  target: LatLng(37.43296265331129, -122.08832357078792), zoom: 14),
              onMapCreated: (GoogleMapController googleMapController) {
                setState(() {
                  myMarkers.add(Marker(
                      markerId: MarkerId('1'),
                      position: LatLng(19.082089, 72.877497),
                      infoWindow: InfoWindow(
                        title: 'Hello World',
                        snippet: 'please share Address',
                      ),
                      onTap: () {
                        print('Marker tabes');
                      },
                      icon: bitmapDescriptor));
                });
              },
              markers: myMarkers,
              polygons: myPolygon(),
            ),
            Container(
              alignment: Alignment.topCenter,
              child: Image.asset('assets/images/d.jpg'),
            ),
            Container(
              child: Text(
                'Flutter Google Maps',
                style: TextStyle(fontSize: 35.0, fontWeight: FontWeight.bold),
              ),
              alignment: Alignment.bottomCenter,
            )
          ],
        ));
  }
}

Happy Coding :)
....................................................................................................................................................................................................................................
Example :#8 [Flutter Geolocation - Fetch the User's Current Location ] 

Library

geolocator: ^6.1.8
https://pub.dev/packages/geolocator

Add the following to your "gradle.properties" file:

android.useAndroidX=true
android.enableJetifier=true

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
.............
Code here
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String latitudeData = "";
  String longitudeData = "";

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

  getCurrentLocations() async {
    final geolocator = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
       setState(() {
      latitudeData = '${geolocator.latitude}';
      longitudeData = '${geolocator.longitude}';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Geolocation'),
        centerTitle: true,
      ),
      body: Center(
        child: Column(
          children: [
            Text(latitudeData),
            Text(longitudeData),
          ],
        ),
      ),
    );
  }
}

Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #9[ Get User Current Location Using Flutter]

Add dependencies -
https://pub.dev/packages/geolocator/install
  geolocator: ^6.1.13

AndroidManifest.xml
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

  <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

Important url for
https://developer.android.com/training/basics/network-ops/connecting
https://developer.android.com/training/location/permissions#reminder-background-location-grant

.............................................
Code Here
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  String locationsMessage = "";

  Future<void> getCurrentLocations() async {
    final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print(position);

    final lat = position.latitude;
    final lon = position.longitude;
    setState(() {
      locationsMessage = "Latitude : $lat, Longitude: $lon";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Location Services"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.location_on,
              size: 45.0,
              color: Colors.blue,
            ),
            const SizedBox(height: 20.0),
            const Text('Get user Locations',
                style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold)),
            const SizedBox(height: 20.0),
            Text("Position: $locationsMessage"),
            FlatButton(
              onPressed: () => getCurrentLocations(),
              color: Colors.black,
              child: const Text("Open Maps",
                  style: TextStyle(
                      color: Colors.white, fontWeight: FontWeight.bold)),
            )
          ],
        ),
      ),
    );
  }
}

Another Code 
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String locationMessage = "";

  Future<void> getLocations() async {
    final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print(position);
    setState(() {
      locationMessage = "${position.latitude}, ${position.longitude}";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hello'),
      ),
      body: Center(
        child: Column(
          children: [
            Text(locationMessage),
            RaisedButton(
              onPressed: () => getLocations(),
              child: const Text("Get Address"),
            ),
          ],
        ),
      ),
    );
  }
}
Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #10[ Get User Address In Flutter]

dependencies
  geolocator: ^6.1.13
  geocoder: ^0.2.1

https://pub.dev/packages/geocoder/install
https://pub.dev/packages/geolocator/install

Code Here

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoder/geocoder.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Position positions;
  StreamSubscription<Position> streamSubscription;
  Address address;

  @override
  void initState() {
    super.initState();
    streamSubscription = Geolocator.getPositionStream(
            distanceFilter: 10, desiredAccuracy: LocationAccuracy.high)
        .listen((Position position) {
      setState(() {
        positions = position;
        final coordinates = Coordinates(position.latitude, position.longitude);
        convertCoordinateToAddress(coordinates)
            .then((value) => address = value);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("Get Address")),
      body: Center(
        child: Column(
          children: [
            Text("Long ${positions?.latitude ?? '-'},${positions?.longitude ?? '-'}"),
            //Text("${address?.addressLine ?? '-'}"),
            Text("Current Address : ${address?.addressLine?? '-'}"),
            Text("Dist : ${address?.locality?? '-'}"),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    streamSubscription.cancel();
  }

  Future<Address> convertCoordinateToAddress(Coordinates coordinates) async {
    final addresses =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    return addresses.first;
  }
}
Note  - Testing device should be physical device
and update Google playstore apps or clear cache
 

Another Code Here

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() => MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  String address1 = "";
  String address2 = "";

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

  Future<void> getAddress() async {
    final coordinates = Coordinates(12.902030, 77.593540);
    final address =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    setState(() {
      address1 = address.first.addressLine;
      address2 = address.first.locality;
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Get User Locations!"),
      ),
      body: Center(
        child: Column(
          children: [
            Text(address1),
            Text(address2),
          ],
        ),
      ),
    );
  }
}
...........................................
Another Code 

import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:geolocator/geolocator.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String locationMessage = "";
  String address1 = "";
  String address2 = "";

  Future<void> getLocations() async {
    final position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.high);
    print(position);
    setState(() {
      locationMessage = "${position.latitude}, ${position.longitude}";
    });
  }

  Future<void> getAddress() async {
    final coordinates = Coordinates(37.4219983, -122.084);
    final addresses =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    
    setState(() {
      address1 = addresses.first.addressLine;
      address2 = addresses.first.locality;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Hello'),
      ),
      body: Center(
        child: Column(
          children: [
            Text(locationMessage),
            RaisedButton(
              onPressed: () => getLocations(),
              child: const Text("Get Longitude"),
            ),
            Text(address1),
            Text(address2),
            RaisedButton(
              onPressed: () => getAddress(),
              child: const Text("Get Address"),
            ),

          ],
        ),
      ),
    );
  }
}

Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #11[]

https://pub.dev/packages/google_maps_flutter
google_maps_flutter 1.1.1 

Google Cloud console
https://console.cloud.google.com/apis/dashboard?project=fluttermaps-302110




API Key



Choose Here as Restrict Key




Maps for Android
Maps for iOS










Happy Coding :)
....................................................................................................................................................................................................................................
Example:  #12[]

import 'dart:core';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart' as geocoder;
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  
  @override
  HomeState createState() => HomeState();
}

class HomeState extends State<Home> {
   GoogleMapController googleMapController;
   Position position;
   String addresslocations;
   String country;
   String postalCode;

  Map<MarkerId, Marker> markers = Map<MarkerId, Marker>();

  void getMarkers(double lat, double long) {
    MarkerId markerId = MarkerId(lat.toString() + long.toString());
    Marker marker = Marker(
        markerId: markerId,
        position: LatLng(lat, long),
        icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan),
        infoWindow: InfoWindow(snippet: 'Address'));
    setState(() {
      markers[markerId] = marker;
    });
  }

  Future<void> getCurrentLocations() async {
    Position currentPosition =
        await GeolocatorPlatform.instance.getCurrentPosition();
    setState(() {
      position = currentPosition;
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Google Maps'),
        ),
        body: Container(
          child: Column(
            children: [
              SizedBox(
                height: 600.0,
                child: GoogleMap(
                  onTap: (tapped) async {
                    final coordinates = new geocoder.Coordinates(
                        tapped.latitude, tapped.longitude);

                    var address = await geocoder.Geocoder.local
                        .findAddressesFromCoordinates(coordinates);
                    var firstAddress = address.first;

                    getMarkers(tapped.latitude, tapped.longitude);
                    await FirebaseFirestore.instance
                        .collection('locatioon')
                        .add({
                      'latitude': tapped.latitude,
                      'longitude': tapped.longitude,
                      'Address': firstAddress.addressLine,
                      'Country Code': firstAddress.countryName,
                      'PostalCode': firstAddress.postalCode
                    });
                    setState(() {
                      country = firstAddress.countryName;
                      postalCode = firstAddress.postalCode;
                      addresslocations = firstAddress.addressLine;
                    });
                  },
                  mapType: MapType.hybrid,
                  compassEnabled: true,
                  trafficEnabled: true,
                  onMapCreated: (GoogleMapController controller) {
                    setState(() {
                      googleMapController = controller;
                    });
                  },
                  initialCameraPosition: CameraPosition(
                      target: LatLng(position.latitude.toDouble(),
                          position.longitude.toDouble()),
                      zoom: 15.0),
                  markers: Set<Marker>.of(markers.values),
                ),
              ),
              Text('Address: $addresslocations'),
              Text('Postal: $postalCode'),
              Text('Country: $country'),
            ],
          ),
        ));
  }

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


Happy Coding :)

...............................................................................................................................................................................................................................


...............................................................................................................................................................................................................................


...............................................................................................................................................................................................................................

...............................................................................................................................................................................................................................