In Flutter, we use the Dart programming language to build cross-platform applications. The Dart package is like a library you might be used to installing for node.js projects using NPM or YARN. These packages are built by Flutter developers for Flutter developers.

In this tutorial, we will show you how to build Dart packages and share them with other Flutter developers around the world.

We will introduce the following with practical examples.

  • What is the Dart package?
  • Flutter Project requirements
  • Dart package type
  • Create a Flutter/Dart package
  • Initialize a Git repo
  • Write a Flutter widget
  • Test your Flutter package
  • Publish and share your Flutter packages

What is the Dart package?

The Dart package helps us solve problems and create workarounds for problems without having to write code from scratch ourselves.

For example, suppose we are building a Flutter application and we find that we need to upload an image from the local file system and display it in the application. It would be tedious and time-consuming to implement this feature ourselves.

It’s likely that a developer somewhere has built a Dart package for Flutter to handle image extraction and display functions for us. All we have to do is install the package and use its methods and classes to find and display images. This gave us more time to focus on the core business logic of our application.

Flutter Project requirements

To continue with this tutorial, make sure that the Flutter SDK is installed on your machine.

The Flutter SDK is used to build, compile, and run Flutter projects. To install Flutter, go to the official Flutter website and download the appropriate SDK for your operating system.

  • Windows
  • macOS
  • Linux
  • Chrome OS

Dart package type

There are two types of packages available in Dart: the plain Dart package and the plug-in package.

  • The Dart package is a generic package written in Dart. They are independent of any native platforms, such as Android and iOS. These packs are specific to the Flutter and can only be used on the Flutter frame.
  • The plug-in package is platform-specific and contains apis written in Dart code. These packages can be written for Android (using Kotlin or Java), iOS (using Swift or Objective-C), Web, macOS, Windows, or Linux.

In this tutorial, we will demonstrate how to create a Dart package.

Create a Flutter/Dart package

To create a Flutter package, run the following command.

flutter create --template=package flutter_pkg

Copy the code
  • createSubcommands are used to create a Flutter project or package. In this case, it will create a Flutter package
  • --template=packageFlag tells it to create a Flutter package.
  • flutter_pkgIs the folder where the Flutter package is created. You can call it whatever you want

The command will run like this.

Creating project flutter_pkg... flutter_pkg/LICENSE (created) flutter_pkg/test/flutter_pkg_test.dart (created) flutter_pkg/flutter_pkg.iml (created) flutter_pkg/.gitignore (created) flutter_pkg/.metadata (created) flutter_pkg/pubspec.yaml (created) flutter_pkg/README.md (created) flutter_pkg/lib/flutter_pkg.dart (created) flutter_pkg/.idea/libraries/Dart_SDK.xml (created) flutter_pkg/.idea/modules.xml (created) flutter_pkg/.idea/workspace.xml (created) flutter_pkg/CHANGELOG.md (created) Running "flutter pub get" in flutter_pkg... 5.3 S Wrote 12 files. All done! Your package code is in flutter_pkg/lib/flutter_pkg.dartCopy the code

The main or entry file for this package is lib/flutter_pkg.dart. Flutter sets the main file to be the same as the package name with the.dart extension. Our package name is flutter_pkg, so the main file will be flutter_pkg.dart. If the package name is modalpicker, the main file will be modalpicker.dart.

Let’s take a look at some of the files and folders we generated to see what they do.

  • pubspec.yamlContains information about the Flutter package and the dependencies of the project. It also allows us to specify assets to be added to a Flutter project, such as images, fonts, and so on.
  • .gitignoreTell Git which files in the Flutter project to ignore when pushing our code to the repository.
  • README.mdContains general information about the project written in Markdown. This file describes, among other things, how to install, run, and contribute to the project.
  • CHANGELOG.mdThis is where we add our changes to the project. This file is also written in Markdown

Initialize the Git repo

Before we can move forward, we need to initialize a Git repo in our project. This helps when we need to push our package to pub.dev.

Run the following code.

echo "# flutter_pkg" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin [email protected]:flutter-prjs/flutter_pkg.git
git push -u origin main

Copy the code

We will include a pubspec.yaml in our homepage or Repository field. In homepage, we will add the Git repo URL for our package project. We’ll also add a description to give developers a clear description of what this package does.

Name: Flutter_pkg description: A new Flutter package with A customized TextButton.version: 0.0.1 author: Chidume Nnamdi homepage: https://github.com/flutter-prjs/flutter_pkgCopy the code

Write a Flutter widget

Next, we will create a custom button style based on our preferences.

Clear the original code generated by Flutter in lib/flutter_pkg.dart. Then, add the CustomButton Widget.

library flutter_pkg; import 'package:flutter/material.dart'; class CustomButton extends StatelessWidget { var onPressed; final Widget child; var style; CustomButton({Key key, @required this.onPressed, this.child, this.style}) : super(key: key); @override Widget build(BuildContext context) { return TextButton( onPressed: onPressed, style: Textbutton. styleFrom(padding: const EdgeInsets. All (16.0), primary: Colors. White, backgroundColor: Color. Blue, elevation: 9.0, textStyle: const textStyle (fontSize: 20,), child: child); }}Copy the code

The library Flutter_pkg code sets the name of our package to Flutter_pkg.

First, we import the Flutter Material package — the root of all Flutter applications. Next, we create a CustomButton class that extends the StatelessWidget class. This allows our CustomButton Widget to not hold or manage local state.

We have three properties that the CustomButton Widget constructor will receive.

  • onPressed– when theCustomButtonThis function is called when the widget is pressed or clicked.
  • style– This property will save the user’s custom style for the button. Users may decide to design ours to suit their tastesCustomButtonWidget, so they code the style and passstyleProperty passes it toCustomButtonThe widget.
  • child– This is aCustomButtonWidget tree for widgets. This tree is usually oneTextWidget that displays text on a button

The Build method renders a TextButton and styles the button as follows.

  • padding– Filler is set to16.0All sides of the unit
  • primary– The main color of the button is set to blue
  • backgroundColor– The background color of the button is set to blue
  • elevation– Button shadow has been raised to9.0The unit.
  • textStyle– The font size is set to 20 units to make the button appear larger.
  • child– This property is renderedCustomButtonWidget tree for widgets.

Our custom button is just like a smaller version of the [TextButton] (https://blog.logrocket.com/new-material-buttons-in-flutter/#textbutton). This button renders a custom TextButton. In our CustomButton, we added TextButton padding, Levation, background color, and text style.

To use this widget, enter the following.

CustomButton(
    onPressed: _incrementCounter,
    child: const Text("Click me")
),

Copy the code

Test your Flutter package

We will need to test our package to see if it works. To do this, we must create a Flutter project in our project.

flutter create example

Copy the code

In our Flutter_pkg project, we will create an Example folder.

Next, we will install our Flutter_pkg in the Example Flutter project. Since the package has not been published to pub.dev, we will refer to the local path.

Open pubspec.yaml in the Example project and add this line.

dependencies: flutter: sdk: flutter flutter_pkg: path: .. /Copy the code

path: .. / Tell Flutter from path.. Gets the Flutter_pkg dependency in / – that is, from its parent folder.

Open lib/main.dart and add the following code to the _MyHomePageState widget.

class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), CustomButton( onPressed: _incrementCounter, child: const Text("Click me") ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); }}Copy the code

We imported the Flutter_Pkg package, and then we set the CustomButton Widget between the two Text widgets.

Run the Example project by running Flutter Run on the command line. If you’re using VS Code, right click on the lib/main.dart file and click “Run without debugging”.

Our application will look like this.

Very good! Our software package is working. Now we can publish it to pub.dev so that other developers can use our package.

Publish and share your Flutter packages

Now that we know our Dart package is working, we can now publish it to pub.dev so other developers can use our package.

Before we release our package, let’s add a LICENSE to the LICENSE file.

Copyright (c) 2021 Chidume Nnamdi
Permission is hereby granted to use this software as deemed fit.

Copy the code

Next, we’ll push our changes to Git. Run the following code.

git add . && git commit -m "Made some changes" && git push

Copy the code

Now it’s time to release our package.

flutter packages pub publish

Copy the code

Something like this will appear.

Publishing flutter_pkg 0.0.1 to https://pub.flutter-io.cn:
|-- .gitignore
|-- .metadata
|-- CHANGELOG.md
|-- LICENSE
|-- README.md
|-- example
...

Copy the code

At the bottom, it will require authorization if you haven’t already obtained it on pub.dev.

Pub needs your authorization to upload packages on your behalf. In a web browser, go to https://accounts.google.com/o/oauth2/auth?access_type=offline&... wpFwBAMgkc&code_challenge_method=S256&scope=openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email Then click "Allow access". Waiting for your authorization...Copy the code

You will then have to Click the link in the terminal above (Ctrl + Click). Finally, you’ll be prompted to authorize access through the Gmail account of your choice.

Note: Flutter says that releases are forever, meaning packages cannot be unpublished.

See the published packages associated with this demo on pub.dev.

conclusion

We’ve covered a lot of ground in this tutorial. We started with an introduction to the packages in Dart, what they are, and how they are designed to share code with other developers.

Later, we learned how to build scaffolding for the Flutter package project and how to code the package. Next, we learned how to test our Flutter packages locally, and finally, how to publish our Flutter packages to pub.dev.

The postHow to create Dart packages for Flutterappeared first onLogRocket Blog.