Day 4: Understanding Widgets and Building Your First UI

Hemant Kumar Prajapati
7 min read1 day ago

--

Welcome to Day 4 of “A Developer’s Journey with Hemant”! 🎉 Today, we’re diving into the heart of Flutter development — widgets. 🧩 Widgets are the building blocks of every Flutter app, and mastering them is key to creating beautiful, responsive UIs. 🌟

.

In this session, we’ll explore different types of widgets, learn how to combine them to build a functional UI, and walk through creating your first interface from scratch. 📱 Whether you’re arranging text, images, or interactive elements, this guide will help you become a Flutter UI expert. 🚀

.

Get ready to transform your ideas into reality, one widget at a time! 💪✨

|📚 What Are Widgets?

🎭 Widgets are the stars of your Flutter app. Each one plays a role, and together they bring your UI to life. As the director 🎬, you decide how they look and interact. Let the show begin! 🌟

  • 📦 Everything is a Widget: In Flutter, the user interface (UI) is built by combining multiple widgets. Whether it’s a button, text, image, or even the layout structure, everything in Flutter is a widget.
  • 🏗️ Composition Over Inheritance: In Flutter, you build complex UIs by combining simple widgets, like stacking building blocks. This method is easier and keeps your code flexible.

💡 Tip: Understanding this widget-based architecture is key to becoming proficient in Flutter. Think of widgets as Lego blocks that you can stack and arrange to build your app.

|🔄 Stateless vs. Stateful Widgets

🌱 In Flutter, widgets come in two flavors: Stateless and Stateful. Stateless widgets are simple — they stay the same. But Stateful widgets? They can change and react to what’s happening. 🎭 Knowing which one to use is key to keeping your app dynamic and responsive!

🟢 StatelessWidget:

  • Immutable and does not store any state.
  • Perfect for static content that doesn’t change dynamically.
  • Example: A Text widget that displays a simple string.
class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyStatelessWidget(),
);
}
}

class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text('Hello, Stateless Widget!')));
}
}

🔴 StatefulWidget:

  • Mutable and can change during the app’s lifetime.
  • Ideal for dynamic content that changes in response to user interactions or other events.
  • Consists of two classes: the StatefulWidget itself and the State class where the mutable state is stored.
class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyStatefulWidget(),
);
}
}

class MyStatefulWidget extends StatefulWidget {
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int counter = 0;

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: Text('Counter: $counter')),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
counter++;
});
},
child: Icon(Icons.add)),
);
}
}
  • 💡 Tip: Use StatelessWidget for simple, static UIs and switch to StatefulWidget when you need to handle interactions or update the UI dynamically.

|🧩 Essential Flutter Widgets to Know

🌟 Dive into the world of Flutter with must-know widgets! Each one has its own superpower, from displaying text to handling user input. 🚀 Master these essentials, and you’ll have the tools to build stunning and functional UIs.

📝 Text:
The Text widget displays a string of text on the screen. It supports various styling options such as font size, color, and weight. It's one of the most basic widgets you'll use frequently in any Flutter app.

Text(
'Hello, Flutter!',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
);

🔘 Button Widgets:

  • ElevatedButton: A raised button with shadow, typically used for primary actions in your app. It’s great for drawing attention to the main actions.
ElevatedButton(
onPressed: () {
// Action when pressed
},
child: Text('Press Me'),
);
  • TextButton: A flat button with no elevation, usually used for less prominent actions or secondary choices.
TextButton(
onPressed: () {
// Action when pressed
},
child: Text('Tap Me'),
);
  • IconButton: A button that contains an icon instead of text, often used in app bars or for compact actions like deleting or editing.
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
// Action when pressed
},
);

📦 Container:
The Container widget is one of the most versatile widgets in Flutter. It can contain other widgets and allows you to apply styles like padding, margin, borders, and background color. It's commonly used to structure your layout and style individual elements.

Container(
padding: EdgeInsets.all(16.0),
margin: EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(10.0),
),
child: Text('Styled Container'),
);

🖼️ Image:
The Image widget displays an image in your app. You can load images from various sources, including assets, network URLs, or local files. It's essential for adding visual elements like logos, icons, and photos to your app.

Image.network(
'https://flutter.dev/assets/homepage/carousel/slide_1-bg-2e24b3b7e9f6ad94f87fd945015127fe90c20c926a5d8ed155b2cc1cfc2127f7.jpg',
);

|🛠️ Layout Widgets:

  • Column: Aligns widgets vertically in a single column. Useful for stacking widgets on top of each other.
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('First Item'),
Text('Second Item'),
],
);
  • Row: Aligns widgets horizontally in a single row. Ideal for placing widgets side by side
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text('Left'),
Text('Center'),
Text('Right'),
],
);
  • Stack: Overlays widgets on top of each other. It’s great for creating layered UIs, like adding text on top of an image.
Stack(
children: <Widget>[
Image.network('https://flutter.dev/assets/homepage/carousel/slide_1-bg-2e24b3b7e9f6ad94f87fd945015127fe90c20c926a5d8ed155b2cc1cfc2127f7.jpg'),
Text('Overlay Text'),
],
);

Expanded & Flexible: These widgets help manage how child widgets expand or contract within a Row or Column. Expanded fills the available space, while Flexible allows a widget to take up space based on its flex value without forcing it to fill the remaining space.

Expanded(
child: Container(
color: Colors.red,
child: Text('Expanded Widget'),
),
);

💡 Tip: Learn to use Container in combination with layout widgets like Row, Column, and Stack to create complex UIs.

🏗️ Building a Simple UI

  • 🔲 Scaffold: The foundation for your app’s UI, providing a structure with app bars, drawers, and floating action buttons (FABs).
Scaffold(
appBar: AppBar(
title: Text('My First UI'),
),
body: Center(
child: Text('Hello, World!'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
child: Icon(Icons.add),
),
);

🔢 Handling State: Use the setState method in StatefulWidget to update the UI when the state changes. This ensures the UI reflects the latest state.

void _incrementCounter() {
setState(() {
_counter++;
});
}

💡 Insight: Understanding how StatelessWidget and StatefulWidget work together will make your app more dynamic and interactive. Practice building different UIs by experimenting with these widgets.

|🛠️ Tips and Best Practices

💡 Unlock the secrets to Flutter success with top tips and best practices! These golden rules will help you write cleaner code, avoid common pitfalls, and make your app shine. 🌟 Get ready to elevate your development game! 🚀

  • 🔄 Hot Reload: Take advantage of Flutter’s hot reload feature to instantly see changes in your app without restarting. This boosts productivity and speeds up the development process.
  • 📐 Widget Tree Organization: Keep your widget tree clean and organized. Break down complex UIs into smaller, reusable widgets to enhance readability and maintainability.
  • 🎨 Consistent Design: Use themes and consistent styles across your app to ensure a unified look and feel. Flutter allows you to define and reuse styles easily.

💡 Pro Tip: Familiarize yourself with Flutter’s documentation. It’s a comprehensive resource that provides detailed explanations and examples of every widget and feature.

🌟 Enjoyed this tutorial?

For more tips, tutorials, and insights into Flutter, be sure to follow my Medium blog! Stay connected, and let’s continue building amazing things together.

This is just Part 4: Ping me on other platforms… too….

👉 Follow me:

Happy coding! 🎉 !! Happy Flutter !!

💬 Comment Section is Open!

Share your thoughts or ask questions below.

👏 Applaud if you enjoyed this!

Your claps help others find this content.

➕ Follow for more!

Stay updated with more tips and tutorials.

--

--

Hemant Kumar Prajapati

Flutter Developer and Influencer || Running Habithook || Startup Growth