Adding a new package to Flutter Project

Flutter has lot of external packages available which can greatly helps us to easily build our app. In this article we gonna look, how we can add an external package to our flutter project.

Here we are demonstating this by adding a geo location package to our flutter project.

Firstly go to the package webpage, https://pub.dev/packages/geolocator

Then we have to go to the installing section

And copy the dependency details: geolocator: ^6.2.0

We need to copy and paste this to the pubspec.yaml file

Then Click pub.get

Now after successfully adding it, we can see it in the External Library section

Using the Geo Location Package

  • Add Android Permission to AndroidManifest.xml

Android Location access permission code for Flutter

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

  • Add iOS Permission to info.plist

iOS Location access permission code for Flutter

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>

main.dart

import 'package:flutter/material.dart';
import 'package:clima/screens/loading_screen.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}

loading_screen.dart

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

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {
  void getLocation() async {
    Position position = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
    print(position);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: RaisedButton(
          onPressed: () {
            getLocation();
          },
          child: Text('Get Location'),
        ),
      ),
    );
  }
}

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *