Just like any other platform, there would be time when you created a piece of code that you may want to use in multiple projects of yours but you do not want to copy paste the code. Because copy pasting will raise several problems, one of which is fixes in that piece of code. If you do a fix, you have to copy and paste the fix in all of the projects it is being used.
To solve this issue it is recommended to create your packages. Here are the basic steps of creating a Flutter package:
- Create a new Flutter package: Use the
flutter create
command to create a new Flutter package. This will generate a directory structure for your package. - Define the package: In the
pubspec.yaml
file of your package, define the package\’s name, description, version, and dependencies. - Create your package\’s code: Write the code for your package\’s functionality in the
lib
directory. You can organize your code into subdirectories if needed.
library card_button;
import \'package:flutter/material.dart\';
class CardButton extends StatelessWidget {
final String label;
final VoidCallback onPressed;
CardButton({required this.label, required this.onPressed});
@override
Widget build(BuildContext context) {
return Card(
child: InkWell(
onTap: onPressed,
child: Padding(
padding: EdgeInsets.all(16.0),
child: Text(
label,
style: TextStyle(fontSize: 16.0),
),
),
),
);
}
}
- Export your package\’s API: In the
lib
directory, create a file namedyour_package_name.dart
and export the public API of your package. - Publish your package: Publish your package to the official Flutter package repository,
pub.dev
, so that others can use it in their own projects. You can use theflutter packages pub publish
command to publish your package. - Update your package: As you add new features or fix bugs in your package, update the version number in the
pubspec.yaml
file and publish a new version of your package.
Once your package is published on pub.dev
, other developers can add it to their Flutter projects by including it as a dependency in their project\’s pubspec.yaml
file.
Leave a Reply