Definition (Programming): In Flutter, a Widget is the fundamental building block of the user interface. Everything you see on the screen in a Flutter app—texts, buttons, images, layouts—are widgets.
Real-life Example: Think of widgets like LEGO blocks. Each LEGO piece (widget) has a specific shape and purpose, and when you combine them, you build complex structures—your app’s UI.
// A simple Flutter app using a StatelessWidget
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('My First Widget')),
body: Center(
child: Text('Hello, Flutter!'),
),
),
);
}
}
Explanation:
StatelessWidget is used when the widget does not change its state after being built.MaterialApp is the root widget that provides Material Design styling and features.Scaffold sets up the basic visual layout structure like app bar and body.// A StatefulWidget example to update UI dynamically
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: CounterWidget(),
);
}
}
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State {
int count = 0;
void increment() {
setState(() {
count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter Example')),
body: Center(child: Text('Count: \$count')),
floatingActionButton: FloatingActionButton(
onPressed: increment,
child: Icon(Icons.add),
),
);
}
}
Why use StatefulWidget?
StatefulWidget when the UI changes over time or reacts to user input.count variable updates every time the user taps the button, triggering setState() to rebuild the UI.For more detailed Flutter widget info, visit the official Flutter Widgets documentation.