flutter package

How to Build and Release Your Own Flutter Package

Getting Started with Flutter Packages


By developing several application using Flutter Framework, as a developer, we get to know that there are a couple of things which we can reuse across the different projects for same or similar functionalities. To achieve such reusability, there are 2 different approaches that we can take:

•Have that feature or UI as custom component and use same file by copying it to required project.

•Make it like accepting values in two different groups: required and optional. For optional parameters, we can have some pre-defined values if not passed. Now use this component as a custom widget to be used from separate Flutter Package.

The second option is pretty good to use that component as separate Flutter Package. The benefits of this is we can always extend it as per our requirements and also update it along with updating Flutter framework.

In this article, we’re going to learn how we can develop our own Flutter package and how to utilize it as best for ongoing Flutter Projects. For simplicity, we’re only going to define a method in package to accept:

•context – to have proper context from calling screen.

•title – title for alert dialog.

•message – content for alert dialog.

We’re going to define a class named “SFLAlert” with a simple method displaySimpleAlert to display dialog with only title and content on it.

Step 1 Create a Flutter Package Project


flutter package

Just like any other Flutter application, we need to start with Flutter package. Give additional details like the name of the package (SFLFlutterPacakge) and other things. Once everything is done, we’re ready to add our required functionality.

Step 2 Feature Development


Similar to normal Flutter application architecture, the same architecture can be used for Flutter package. Inside lib folder, create a folder named “sfl_alert” and create a dart class SFLAlert.

Now create a method named “displaySimpleAlert” with the parameters as we discussed earlier as displayed below.

///Display Simple Alert Dialog 
static void displaySimpleAlert({ 
  required BuildContext context, 
  required String title, 
  required String content, 
}) { 
  	///Alert Dialog Implementation 
}

We have kept these parameters as required parameters as we make sure we have passed context and content to be displayed to this method call.

Now to display AlertDialog, we only need to implement showDialog method of Flutter framework with required parameter as shown below.

///Alert Dialog Implementation 
showDialog( 
context: context, 
  builder: (context) => AlertDialog( 
    title: Text( 
      title, 
      textAlign: TextAlign.center, 
      style: Theme.of(context).textTheme.headline5!.copyWith( 
            fontWeight: FontWeight.bold, 
          ), 
    ), 
    content: Text( 
      content, 
      style: Theme.of(context).textTheme.headline6!.copyWith( 
            fontWeight: FontWeight.w300, 
          ), 
    ), 
  ), 
);

Now with this, the feature development is done. We know this is the basic and simple one, but it will be easy to understand the simplicity of Flutter package building. Next, we have to make this feature available to use it in another Flutter projects.

Step 3 Export Developed Feature


Inside lib folder, create a dart file named the same as our developed package name “sfl_flutter_package.dart.” On top of the file, add a line defining this project as a library as shown below.

library sfl_flutter_package;

Now, write a line to export our Step 2 developed feature using below line.  

 

///SFL Alert 
export 'src/sfl_alert/sfl_alert.dart';

This will make our SFLAlert class to be imported from flutter projects where this package is used.

Step 4 Add an Example to Flutter Package


Next, to test during development and to give best practice of more insights for proper utilization of features available in package, we need to add a Flutter application giving usage guidelines of features available in package. So, create a Flutter application named example inside our package directory. It must look like below.

flutter package

Now, in this example app, we’ll display an entry screen displaying a button on center of the screen. Tapping on this butto,n we’ll be calling feature we developed in our package to display an AlertDialog. But before that, we need to add our package to be used in this example flutter application.

To do so, we need to update pubspec.yaml file of example app as shown below.

dependencies: 
  flutter: 
    sdk: flutter 
 
  sfl_flutter_package: 
    path: ../

This will reference our package same as the other packages we are using from pub.dev.

Next, as mentioned earlier, we’ll be displaying an AlertDialog by calling method developed in Flutter package with a tap on a button being displayed in center of screen. Check below code.

class SFLAlertDemo extends StatelessWidget { 
  @override 
  Widget build(BuildContext context) { 
    return Scaffold( 
      appBar: AppBar( 
        title: Text('SFL Alert Demo'), 
        centerTitle: true, 
      ), 
      body: Container( 
        alignment: Alignment.center, 
        child: TextButton( 
          child: Text('Display Simple Alert'), 
          onPressed: () => SFLAlert.displaySimpleAlert( 
context: context, 
title: 'Alert', 
content: 
    'You\'re viewing alert of Flutter Package triggered from Flutter Application.', 

), 
      ), 
    ); 
  } 
}

Here we do have only single TextButton on center of the screen, where tapping on it, will call defined method of package class SFLAlert.displaySimpleAlert with required parameters context, title and content. Below is the result we’ll get.

As a result, we have successfully developed a Flutter package and consumed in it a Flutter application to display an alert dialog with title and content text on the screen. To extend it, we can also define other parameters for:

•Styling of text being displayed

•To display an optional icon beside title

•To display positive and negative feedback button to perform some action further.

And a lot more…

More Flutter Package Action Items


Along with creating and consuming a Flutter package, there are a few things which we need to take care as specified below.

pubspec.yaml file of flutter package

This file contains some information about our Flutter package like name, description, version, author, and homepage which we can add to provide more details to the consumers.

CHANGELOG.md

This file contains the changes of specific version as we move further in our package life span.

LICENSE

Choose an open-source license for your Flutter package. Mostly we can go with MIT LICENSE.

Publishing a Package

To do this, we have to push our package to Github repository. Once done we can use below command to publish out package to pub.dev

  • Flutter packages pub publish

Executing this will give a link in command line to verify our email address and pub.dev send us an email about our package.

Hence, this is how we can create different features in the same package at organization level as well as publish it globally for global developers and keep adding more and more to get the best out of it. We hope you’ve learned more about how to build and release your own Flutter Package. Please come back to Coding with Sunflower Lab to learn more. Until then, happy coding!

Related Posts

10 Essential Real Estate App Features that Enhance Your Business

Employee expense receipt management is the perfect process for RPA because it is logic based and redundant. Let’s

Guide To 7 Best Tech Stack 2023 for Software Development

Employee expense receipt management is the perfect process for RPA because it is logic based and redundant. Let’s


how to use updated flutter button widgets - sunflower lab

How To Use Updated Flutter Button Widgets

Flutter has released new button widgets for mobile app developers.  Who wants to forget about RaisedButton, FlatButton, OutlineButton which provides a simple way to add buttons with or without icon on a screen for our mobile applications? To simplify it, Flutter has updated these all these to ElevatedButton, TextButton, OutlinedButton respectively with parameter as well as styling option updates. Let’s see them one by one.

ElevatedButton

Same as RaisedButton, this widget puts button with elevation on the screen. Required parameters are same, child, onPressed. Child will accept widget to be displayed on button, onPressed will accept a VoidCallBack to be called when a button been pressed/touched.

ElevatedButton( 
  child: Text('Elevated Button'), 
  onPressed: () { 
    	log('Elevated button clicked'); 
  }, 
)

Having same code which we used for RaisedButton we can have same representation with ElevatedButton 

Elevated Button Flutter Button Widget

Now let’s talk about another replacement, TextButton 

TextButton

This one is an alternative of FlatButton, which we’re be using where a tapped action needs to be provided for Text being displayed on screen without any border, elevation or fancy decoration. Required parameters are same child and onPresseed.

TextButton( 
  child: Text('Text Button'), 
  onPressed: () { 
    log('Text button clicked'); 
  }, 
),

Button will be displayed as shown below.  

Text Button Flutter Button Widget

Let’s talk about last, replacement if OutlineButton. 

OutlinedButton

We were using OutlineButton to display a tap action on screen with outline border, without filling area occupied inside this outline border. Required parameters are same, child and onPressed.

OutlinedButton( 
  child: Text('OutlinedButton Button'), 
  onPressed: () { 
    log('OutlinedButton button clicked'); 
  }, 
),

Button will be displayed as shown below. 

OutlinedButton Flutter Button Widget

So, these was the basic details of replacement of button widgets available in Flutter to display different type of buttons for out mobile applications.  

Additional Note

Button with icon which we’re using earlier are same with these updated widgets as well. To have an elevated button with icon use ElevatedButton.icon widget and pass required parameters. Same for outlined button and text button, use OutlinedButton.icon, TextButton.icon respectively. Below are the representations how they will look.

elevated button outlined button text button Flutter button widget

Next, now let’s talk about styling.  

Styling

Styling can be provided to content being displayed on button and as well as to button itself. Previously, we were having different parameters at individual button level to decide different styling properties, but now this can be done by giving a value of ButtonStyle class to style parameter of these updated material buttons. Let’s check them out one by one.

Note: This all property works same for TextButton and OutlinedButton as well. For simplicity, only ElevatedButton is represented in further article.

textStyle

This will define styling of text being displayed on button. It accepts a value of TextStyle class to provide text styling options via MaterialStateProperty. See below.

textStyle: MaterialStateProperty.all<TextStyle>( 
  TextStyle( 
    fontSize: 24.0, 
    fontWeight: FontWeight.w500, 
  ), 
),

elevated button flutter button widget styling

Colors (backgroundColor, foregroundColor, overlayColor, shadowColor) 

These options are available to have required color for specific place.  

  • backgroundColor : for button background. 
  • foregroundColor : for content being displayed on the button. 
  • overlayColor : for ripple being displayed when tapped or long pressed. 
  • shadowColor : for shadow of the button when elevation is greater than 0. 

All of these options, accepts value of Color class via MaterialStateProperty. See below code. 

backgroundColor: MaterialStateProperty.all<Color>( 
  Colors.blueAccent, 
), 
foregroundColor: MaterialStateProperty.all<Color>( 
  Colors.yellow, 
), 
overlayColor: MaterialStateProperty.all<Color>( 
  Colors.red, 
), 
shadowColor: MaterialStateProperty.all<Color>( 
  Colors.green, 
),

elevated button flutter button widget styling 2

elevation 

To provide z index height (elevation) to button we can assign any positive value to it.  

elevation: MaterialStateProperty.all<double>(5.0),

elevated button flutter button widget styling 3

padding 

To give spacing between button border and content being displayed above it this property can be used. It accepts value of EdgeInsets via MaterialStateProperty. 

padding: MaterialStateProperty.all<EdgeInsets>( 
  EdgeInsets.symmetric( 
    horizontal: 20.0, 
    vertical: 15.0, 
  ), 
),

elevated button flutter button widget styling 4

side 

Using this parameter we can even customize border of a button being displayed on the mobile screen. Pass value of BorderSide class via MaterailStateProperty as below and see changes. 

side: MaterialStateProperty.all<BorderSide>( 
  BorderSide( 
    color: Colors.yellow, 
    width: 3.0, 
  ), 
),

flutter button widget

shape 

This parameter is an interesting one as it gives us so many options to be used to have different shapes for a button. See options below,  

BeveledRectangleBorder 

shape: MaterialStateProperty.all<OutlinedBorder>( 
  BeveledRectangleBorder( 
    borderRadius: BorderRadius.circular(20.0), 
  ), 
),

flutter button widget

ContinuousRectangleBorder

shape: MaterialStateProperty.all<OutlinedBorder>( 
  ContinuousRectangleBorder( 
    borderRadius: BorderRadius.circular(20.0), 
  ), 
),

flutter button widget continuous border

RoundedRectangleBorder 

shape: MaterialStateProperty.all<OutlinedBorder>( 
  RoundedRectangleBorder( 
    borderRadius: BorderRadius.circular(20.0), 
  ), 
),

flutter button widget

Circle Border

shape: MaterialStateProperty.all<OutlinedBorder>( 
  CircleBorder(), 
),

flutter button widget

See, this is how this shape parameter changes shape of a material button with different representations.  

So, these are all what we have for updated Flutter material buttons. We hope you learned something new! Stay tuned for our next how-to article. 

Related Posts

10 Essential Real Estate App Features that Enhance Your Business

Employee expense receipt management is the perfect process for RPA because it is logic based and redundant. Let’s

Guide To 7 Best Tech Stack 2023 for Software Development

Employee expense receipt management is the perfect process for RPA because it is logic based and redundant. Let’s