How to Create Widget in Flutter: Simple Guide
In Flutter, you create a widget by defining a class that extends
StatelessWidget or StatefulWidget. Override the build method to return the UI elements as a widget tree.Syntax
To create a widget, define a class that extends either StatelessWidget for static UI or StatefulWidget for dynamic UI. Implement the build method which returns the widget tree representing the UI.
- StatelessWidget: For widgets that do not change state.
- StatefulWidget: For widgets that maintain state and can update UI.
- build method: Returns the UI as a widget tree.
dart
class MyWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Text('Hello Widget'); } }
Output
A text widget displaying 'Hello Widget' on the screen.
Example
This example shows a simple StatelessWidget that displays a centered text on the screen.
dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Simple Widget')), body: Center( child: Text('Hello Flutter Widget!'), ), ), ); } }
Output
App with a top app bar titled 'Simple Widget' and centered text 'Hello Flutter Widget!' in the body.
Common Pitfalls
Beginners often forget to override the build method or return a widget from it. Another common mistake is using StatelessWidget when the UI needs to update dynamically, which requires StatefulWidget.
Also, avoid putting heavy logic inside the build method as it runs often.
dart
class WrongWidget extends StatelessWidget { // Missing build override } class RightWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Text('Correct Widget'); } }
Quick Reference
Here is a quick summary of widget creation:
| Concept | Description |
|---|---|
| StatelessWidget | Widget with immutable UI, no state changes. |
| StatefulWidget | Widget that can change UI dynamically with state. |
| build() | Method that returns the widget tree for UI. |
| runApp() | Function to start the app with a root widget. |
Key Takeaways
Create widgets by extending StatelessWidget or StatefulWidget classes.
Always override the build method to define the UI.
Use StatelessWidget for static UI and StatefulWidget for dynamic UI.
Avoid heavy logic inside the build method to keep UI smooth.
Use runApp() to launch your root widget in the app.