Day 3 - Exploring Flutter Widgets
Welcome back to our daily Flutter updates! Today, on Day 3, we’re diving into one of the most important concepts in Flutter – Widgets. Widgets are the building blocks of a Flutter app, and mastering them is essential to becoming a skilled Flutter developer.
What are Flutter Widgets?
In Flutter, everything you see on the screen is a widget. Whether it’s a text, image, button, or layout, it’s all a widget. They help you design the structure of your app and make it interactive.
Types of Widgets:
- StatelessWidget: These widgets do not change over time. Once created, they remain the same. For example, a static text display.
- StatefulWidget: These widgets can change their state during the app's lifetime. For example, a button that changes color when pressed.
Example Code:
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('Day 3 - Flutter Widgets'),
),
body: Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State {
bool isPressed = false;
void toggleState() {
setState(() {
isPressed = !isPressed;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: toggleState,
child: Container(
width: 200,
height: 200,
color: isPressed ? Colors.green : Colors.blue,
child: Center(
child: Text(
'Press Me',
style: TextStyle(color: Colors.white, fontSize: 24),
),
),
),
);
}
}
Conclusion:
Understanding the difference between StatelessWidget and StatefulWidget is crucial for creating interactive and dynamic apps. Keep experimenting, and stay tuned for more updates on Flutter development!