How to use Dart package in Flutter

Firstly, let me ask you a simple question. It will help you to understand why we need Dart package in Flutter. Secondly, after that we will learn how to use Dart package in Flutter.

Finally we will make a Stateless Widget act like a Stateful Widget with the help of a Dart package.

The question is: if someone wants to help, will you not accept that?

Dart package in Flutter does the same thing.

Many common tasks are done with the help of many Dart packages. Moreover, they are easy to use. Flutter team also keeps some top packages in the Flutter landing page on pub.dev. As a result, you can pick up the top packages quite easily.

In fact, in most Flutter Applications in Android, or iOS, use those packages.

In addition, we can customise any Dart package according to the need of the Flutter App.

In this section we will learn the trick to use a very important Dart package named “provider”. We will also learn what is the alternative to the Stateful Widget. In other words, with the help of Provider package, we can manage the State of the Widget more efficiently.

We have already learned how to build a “Mood Swing App” with the help of Stateful Widget. Not only that, we have also learned how to use Dart package before. Remember the Google Font package?

Therefore, we know the first step.

Add the dependency in the “pubspec.yaml” file first.

We will use the Dart package named “Provider”.

dependencies:
  flutter:
    sdk: flutter
  google_fonts: ^2.3.1
  provider: ^6.0.2

The provider package is just like other shared packages contributed by developers. Meanwhile we can add them to the Dart and Flutter ecosystems.

Consequently, we do not have to write everything from scratch. The Dart package has already done that.

Let us see the code snippet of “Mood Swing App”. Because we had used the Stateful Widget, we had to use setState() method that stores the change of the State.

int leftFaceIndex = 1;
  int rightFaceIndex = 1;
  void changeMood() {
    setState(() {
      leftFaceIndex = Random().nextInt(4);
      rightFaceIndex = Random().nextInt(4);
    });
  }
// for full code please visit the GitHub branch.

As a result, when we press any face, it changes both faces placed in the Row Widget.

Firstly, we create a “model” folder in the root directory. And in that folder, we write the same method. But, without the setState().

import 'dart:math';

import 'package:flutter/material.dart';

class Mood with ChangeNotifier {
  int leftFaceIndex = 1;
  int rightFaceIndex = 1;
  void changeMood() {
    leftFaceIndex = Random().nextInt(4);
    rightFaceIndex = Random().nextInt(4);
    notifyListeners();
  }
}

The provider package basically provides the “Type”. Therefore, we create the “Type” Mood class that stores the instance variables and methods.

At the same time it extends built-in ChangeNotifier class. Instead of the keyword “extend” we have used another keyword “with”. This is known as “mixin-based-inheritance” in Dart. We will discuss it in the next section. Because, as we progress, we will see a lot of mixin-based-inheritance.

The ChangeNotifier will notify the listeners when users press the image. Just as we have seen in the previous Stateful Widgets.

As the provider package helps Flutter to notify the listeners in the child widgets, we need to import it where we need it. We will also import the “Type” that provider provides.

import 'package:provider/provider.dart';

import '../model/mood.dart';

Accordingly, now a Stateless Widget can manage state.

Let us see the full code snippet.

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

import '../model/mood.dart';

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

  @override
  Widget build(BuildContext context) {
    final mood = Provider.of<Mood>(context);
    return Scaffold(
      backgroundColor: Colors.white70,
      appBar: AppBar(
        title: const Text('Mood Swing App'),
      ),
      body: Center(
        child: Row(
          children: [
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    mood.changeMood();
                  },
                  child:
                      Image.asset('images/face${mood.leftFaceIndex + 1}.jpg'),
                ),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(18.0),
                child: GestureDetector(
                  onTap: () {
                    mood.changeMood();
                  },
                  child:
                      Image.asset('images/face${mood.rightFaceIndex + 1}.jpg'),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

We have initialised the “mood” object whom the Provider provides the necessary “Type” Mood.

Thus, now the “mood” object can access all the properties and methods of the Mood class. Not only that, it will only change the State of the associated Widgets.

In our case, the change of State will be reflected only on the Image Widget.

Dart Math library in Flutter App
Dart Math library in Flutter App generates any face with Provider package

As we click, just like before, random faces will appear on the screen.

And to change the State, we no longer use the Stateful Widget. Because we have used the Provider package, we can now manage State with the Stateless Widget.

Mood Swing App in Flutter changes moods reflected on faces
Mood Swing App in Flutter changes moods reflected on faces

You can clone the GitHub repository, and run the same Flutter App in your machine.

However, this is just an introduction to Dart package. In the coming sections we will see more of them.

So stay tuned and keep Fluttering.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

2 responses to “How to use Dart package in Flutter”

  1. […] us consider the “Mood Swing App” that we have built […]

  2. […] With the help of a instance method, which is actually a function, we have already managed State without a Stateful Widget. […]

Leave a Reply