Why Custom Widgets?
- Tailored User Interfaces: Custom widgets allow you to design app components that perfectly match your app’s unique aesthetics and functionality.
- Code Reusability: Once created, custom widgets can be used across your app, promoting code reusability and making maintenance a breeze.
- Abstraction: Widgets abstract the complexity of your UI, making your codebase more organized and comprehensible.
Step 1: Planning and designing
Begin with vision of the custom widget. In this case, we want to create a card widget that can display an image, a headline, and some text. Think about the design in figma or just in your head, define how it should display with different screeen sizes, and decide on the input parameters it needs.
In my typical workflow I do not design the basic widgets in figma, because I can write them fast, but when I need the design to be perfect, or the widget is complex I design it beforehand.
Step 2: Create New Dart File
In your FlutterProject/lib, create a new Dart file for your custom widget. Let’s name it custom_card.dart
.
Step 3: Define the Widget
in newly created file create a stateless or statefull widget, based on the functionality needed-statefull vs. stateless
you can use vs code shortcuts from Flutter Snippets extension – stless or stful
in our case we make a Stateless widget
import 'package:flutter/material.dart';
class CuustomCard extends StatelessWidget {
const CuustomCard({super.key});//constructor
@override
Widget build(BuildContext context) {
return
// Your custom card UI here
}
}
Step 4: replace default constructor with your own constructor with the parameters that you need
In our example with the imageUrl, headline and description.
All the parameters must be final and must be inicialized when you are making calling the constructor. so you can make them required, put default value to them, or make them nullable.
final String imageUrl;
final String headline;
final String description;
const CuustomCard(
{super.key,
required this.imageUrl,
required this.headline,
required this.description});
Step 5: Implement the build
Method
@override
Widget build(BuildContext context) {
return Card(
child: Column(
children: [
Image.network(imageUrl),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
headline,
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(description),
),
],
),
);
}
Step 6: Imlement the widget in your other widgets/pages
CuustomCard(
imageUrl:
"www.imageUrl.com/yourImage",
headline: "Your Headline",
description: "Your card description")
If you follow these steps and customize each one for your needs, you will get the Widget that you need.
Leave a Reply