Future Flutter: WithHer App – Step 1

We are going to build a Weather App. As before, we’ll build it step by step. And this is our first step where we will understand a key concept – Future in Flutter.

But to start with let me assure you one thing first.

It does not take much effort to build a weather app. Let’s name it “WithHer”.

Why it is not difficult?

Because we will build this app with a Flutter Geolocator plugin. In this first step, first we’ll see how we can get the location. As a result, we will print the latitude and longitude.

After that, we will discuss the role of Future in Flutter. By the way, the Future class returns the result of an asynchronous programme.

Why we need to understand the role of Future in getting the location?

We’ll see it in a minute.

However, besides, we need to understand what is asynchronous programming. In addition, we will have to understand two keywords – async and await.

How to the get the location in Flutter?

Firstly, we need to add the dependency of the Geolocator plugin in our “pubspec.yaml” file.

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^1.0.2
  geolocator: ^8.2.0

Secondly, in our Flutter app, we need to import the plugin where we need it.

To make it simple, we will test our weather app in the top-level main() file.

import 'package:geolocator/geolocator.dart';

How do we know a location?

Certainly the latitude and the longitude help us to know the exact location.

And the Geolocator plugin helps us to control how exact we want to be. However, we will keep our priority at the lowest level.

Why?

Because if we want to get the exact location of the user, it may take more time. For that reason, we will make it the lowest. So that, within a radius of 500 meters we can get the weather update.

With reference to that, we must remember one thing. The Geolocator plugin gets the data from internet.

Therefore, it may take an uncertain time. Moreover, the plugin has curtailed our job. If we want to do the low level plumbing and write the whole code we have to write long lines of code.

In addition, we need a certain level of expertise.

But with a few lines of code, the Geolocator plugin has done the same task.

void getLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.lowest);
    print(position);
  }

Actually we’re riding the Geolocator plugin’s back and shoulders and curtail the heavy task. Right?

Geolocator plugin makes our life easier

Let us see the full code snippet now.

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  void getLocation() async {
    Position position = await Geolocator.getCurrentPosition(
        desiredAccuracy: LocationAccuracy.lowest);
    print(position);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'We\'re trying to find the Lat and Lang:',
            ),
            Text(
              'Location',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          getLocation();
        },
        tooltip: 'Get Location',
        child: const Icon(Icons.location_on),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

As we see, the getLocation() method uses two keywords “async” and “await”. Later we have called that method through the onPressed property of the floating action button.

If you want to follow the steps, please clone this branch of GitHub repository.

As we see the above code we find that the two keywords “async” and “await” play an important role here.

We’ll come back to that point in a minute. Before that let’s run the app.

Let’s run the app first

Firstly, we will run the app and see the output.

After that, we will discuss Future in Flutter. As a whole it’s a part of asynchronous programming in Dart.

Future Flutter weather app first example
Future Flutter weather app first example

If we click the floating action button, we will get the latitude and longitude.

However, without the user’s permission we cannot get her location. Right?

Therefore, if we click the floating action button to get the location, the app will seek permission of the user.

Future Flutter weather app second example
Future Flutter weather app second example

Click allow to proceed. And in return it will print the latitude and longitude in the terminal.

Latitude: 22.5892652, Longitude: 88.3056119

Our WithHer App is working perfectly. Now, the time has come to understand what is Future in Flutter. In addition, what is the relation between the Future class and asynchronous programming.

What is asynchronous programming?

Firstly, there are two types of programming. Synchronous and asynchronous.

We need to understand why we need asynchronous programming?

Take a look at the following code which represents synchronous programming.

/// an example of synchronous programme
///

void main() {
  callEveryTask();
}

void callEveryTask() {
  doThisFirst();
  doThisSecond();
  doThisThird();
}

void doThisFirst() {
  print('Doing it first');
}

void doThisSecond() {
  print('Doing it second');
}

void doThisThird() {
  print('Doing it third');
}

When we run the above code, the execution will take synchronously. That means it will execute the first function. Then the second, and lastly it executes the third function.

## output:

Doing it first
Doing it second
Doing it third

The code execution is sequential. But what will happen, if the second function takes much time to execute?

In that case, the third function will have to wait until the second function finishes its task. Right?

Now, consider a case, where the second function is downloading a big file, or gets an image from the internet.

In such cases, user will have to wait to get the result of the third function.

But we don’t want this to happen.

Why?

It does not go with our principle. Because we want to give the user a good experience, we should allow the third function to go ahead and after that the second function may execute.

What is Future in Flutter?

We can achieve this with the help of the Future class in Flutter.

The Future class has a named constructor Future.delayed(). It runs the computation after a certain delay.

Let’s use this Future constructor to delay the second function for 2 seconds.

/// an example of asynchronous programme
///

void main() {
  callEveryTask();
}

void callEveryTask() {
  doThisFirst();
  doThisSecond();
  doThisThird();
}

void doThisFirst() {
  String result = 'First task completed.';
  print('Doing it first');
}

String doThisSecond() {
  String result = 'Second task completed.';
  Duration duration = const Duration(seconds: 2);
  Future.delayed(duration, () {
    print('Doing it second');
    result;
  });
  return result;
}

void doThisThird() {
  String result = 'Third task completed.';
  print('Doing it third');
}

As a result, when we run the code, the third function will execute after the first function executes.

Then, after 2 seconds the second function will execute.

## output ##

Doing it first
Doing it third
Doing it second

This time, we have coded asynchronously. Although we have established a relation between the Future class and asynchronous programming, yet we need to know two keywords – “async” and “await”.

What are async and await?

Just like any other TYPE in Dart, the Future is also a TYPE. As we have learned before that every class is a TYPE of an object, or instance of that class, Future is also a TYPE.

Why?

The reason is simple. It’s a class. Right?

Therefore, we can change the TYPE of the second function from String to Future. But to do that, we have to use two keywords – async and await.

So our previous code changes as follows.

void main() {
  callEveryTask();
}

void callEveryTask() async {
  doThisFirst();
  String secondTask = await doThisSecond();
  doThisThird(secondTask);
}

void doThisFirst() {
  String result = 'First task completed.';
  print('Doing it first');
}

Future doThisSecond() async {
  String result = '..second task completed..';
  Duration duration = const Duration(seconds: 2);
  await Future.delayed(duration, () {
    result;

    print('Please Wait ....');
  });
  return result.toString();
}

void doThisThird(String secondTask) {
  String result = 'Third task completed.';
  print('Doing it third with $secondTask');
}

We have tweaked the previous code a little bit. Now, we have forced the third function to take the output from the second function as its input.

As a result, we need to tell the second function that another function is waiting for your output. Therefore, if you have anything to do, do it now, However, after that, pass the output to the third function.

As a result, we get the following output.

## output ##

Doing it first
Please Wait ....
Doing it third with ..second task completed..

Now, as the second function stops for 2 seconds, the user gets a message like “Please Wait ….“.

Certainly it gives the user a better experience. Because the user knows that she has to wait, she will wait patiently.

This is an introduction to Future and asynchronous programming. Later while we build the weather app, we will discuss it more.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

4 responses to “Future Flutter: WithHer App – Step 1”

  1. […] have been building a weather App. In the first step, the “WithHer” App has used the Geolocator plugin. In addition, we have also used a Stateful […]

  2. […] Till now, we have been progressing a little bit. We have learned how we can use Future in Flutter. […]

  3. […] And before that, we have discussed why we need a Stateful Widget and what is Future in Flutter. […]

  4. […] In the “WithHer” App, which we have been building, we have used Future. In fact, in the first step, we have introduced the concept of Future first. […]

Leave a Reply