Flutter / Flutter Widgets
How to Create Custom Widgets in Flutter
This tutorial teaches you how to create your own custom widgets in Flutter. This is a powerful technique that allows you to write reusable and modular code.
Section overview
5 resourcesExplore the concept of Widgets, the basic building blocks for UI in Flutter.
Creating Custom Widgets in Flutter
1. Introduction
In this tutorial, you will learn how to create your own custom widgets in Flutter, a powerful technique that enables you to write reusable and modular code. By the end of this tutorial, you'll understand how to define and implement custom widgets and how to use them in your Flutter applications.
Prerequisites
- Basic understanding of Dart programming language
- Familiarity with Flutter SDK and widget structure
2. Step-by-Step Guide
In Flutter, everything is a widget. You can think of widgets as the building blocks for your Flutter applications. There are two types of widgets in Flutter: Stateless and Stateful. Stateless widgets are immutable, their properties are final, while Stateful widgets have mutable state.
Creating a Stateless Widget
To create a custom Stateless widget, you need to:
- Create a new class that extends
StatelessWidget. - Override the
buildmethod.
Here is an example:
class CustomText extends StatelessWidget {
final String text;
CustomText(this.text);
@override
Widget build(BuildContext context) {
return Text(
text,
style: TextStyle(fontSize: 24),
);
}
}
In this example, CustomText is a StatelessWidget that takes a String parameter and renders it as a Text widget with a specific style.
Creating a Stateful Widget
Creating a Stateful widget involves a bit more work. You need to:
- Create a new class that extends
StatefulWidget. - Create a separate class that extends
State. - In the
Stateclass, override thebuildmethod.
Here is an example:
class CustomButton extends StatefulWidget {
final String buttonText;
CustomButton({this.buttonText});
@override
_CustomButtonState createState() => _CustomButtonState();
}
class _CustomButtonState extends State<CustomButton> {
@override
Widget build(BuildContext context) {
return RaisedButton(
child: Text(widget.buttonText),
onPressed: () {
print('Button pressed');
},
);
}
}
In this example, CustomButton is a StatefulWidget that takes a String parameter and renders a RaisedButton with the provided text.
3. Code Examples
Example 1: Stateless Widget
This is a simple example of a custom Stateless widget that displays a text message:
class CustomText extends StatelessWidget {
final String message;
CustomText(this.message);
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(10),
),
child: Text(
message,
style: TextStyle(color: Colors.white, fontSize: 20),
),
);
}
}
Example 2: Stateful Widget
This custom Stateful widget is a counter. Clicking the button increments the counter:
class CustomCounter extends StatefulWidget {
@override
_CustomCounterState createState() => _CustomCounterState();
}
class _CustomCounterState extends State<CustomCounter> {
int _count = 0;
void _incrementCounter() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(
'Count: $_count',
style: TextStyle(fontSize: 24),
),
RaisedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
],
);
}
}
4. Summary
In this tutorial, you learned how to create custom widgets in Flutter, including both Stateless and Stateful widgets. You learned the importance of widgets in Flutter and how to use them to build reusable and modular code. The next step in your learning journey could be to explore more complex Stateful widgets and how to manage state in a larger Flutter application.
5. Practice Exercises
- Create a custom Stateless widget that displays an image from a URL passed to it as a parameter.
- Create a custom Stateful widget that toggles between two colors when tapped.
- Extend the
CustomCounterwidget to include decrement and reset buttons.
Solutions
- Custom Stateless Widget
class CustomImage extends StatelessWidget {
final String imageUrl;
CustomImage(this.imageUrl);
@override
Widget build(BuildContext context) {
return Image.network(imageUrl);
}
}
- Custom Stateful Widget
class ColorToggle extends StatefulWidget {
@override
_ColorToggleState createState() => _ColorToggleState();
}
class _ColorToggleState extends State<ColorToggle> {
bool _isBlue = true;
void _toggleColor() {
setState(() {
_isBlue = !_isBlue;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _toggleColor,
child: Container(
color: _isBlue ? Colors.blue : Colors.red,
),
);
}
}
- Extended CustomCounter Widget
class CustomCounter extends StatefulWidget {
@override
_CustomCounterState createState() => _CustomCounterState();
}
class _CustomCounterState extends State<CustomCounter> {
int _count = 0;
void _incrementCounter() {
setState(() {
_count++;
});
}
void _decrementCounter() {
setState(() {
_count--;
});
}
void _resetCounter() {
setState(() {
_count = 0;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Text(
'Count: $_count',
style: TextStyle(fontSize: 24),
),
RaisedButton(
onPressed: _incrementCounter,
child: Text('Increment'),
),
RaisedButton(
onPressed: _decrementCounter,
child: Text('Decrement'),
),
RaisedButton(
onPressed: _resetCounter,
child: Text('Reset'),
),
],
);
}
}
Keep practicing and exploring more functionalities with custom widgets. Happy coding!
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article