Understanding Widgets and Basic Layout
Widgets are the building blocks of Flutter apps. This section dives into different types of widgets, layouts, and how to structure your UI.
Types of Widgets
Stateless Widgets: Do not change once rendered.
Stateful Widgets: Can change dynamically and maintain state across multiple frames.
Basic Layout Widgets
01. Column: Aligns widgets vertically.
02. Row: Aligns widgets horizontally.
03. Container: A versatile widget for adding padding, margins, borders, and backgrounds.
04. Wrap: Aligns widgets in a horizontal or vertical flow. When there's not enough space, the widgets automatically wrap to the next line.
05. Expanded: A widget that expands to fill the available space within a parent widget like a Row, Column, or Flex. It takes up the remaining available space based on the flex factor.
Creating a Layout
Lets create a simple app layout using these basic widgets:
1import 'package:flutter/material.dart';23void main() {4runApp(const MainApp());5}67class MainApp extends StatelessWidget {8const MainApp({super.key});910@override11Widget build(BuildContext context) {12return MaterialApp(13debugShowCheckedModeBanner: false,14home: Scaffold(15appBar: AppBar(16title: const Text("Basic Layout with Wrap and Expanded"),17),18body: Column(19//Aligns widgets vertically.20mainAxisAlignment: MainAxisAlignment.center,21children: <Widget>[22const Text('This is a text widget'),23ElevatedButton(24onPressed: () {},25child: const Text('Click Me'),26),27Container(28//A versatile widget for adding padding, margins, borders, and backgrounds.29padding: const EdgeInsets.all(20.0),30color: Colors.blue,31child: const Text('Container widget with padding'),32),33const Wrap(34// A Wrap widget arranges its children in a flow layout35spacing: 10.0, // Space between children36runSpacing: 5.0, // Space between lines37children: <Widget>[38Chip(label: Text('Chip 1')),39Chip(label: Text('Chip 2')),40Chip(label: Text('Chip 3')),41Chip(label: Text('Chip 4')),42],43),44Row(45//Aligns widgets horizontally.46children: <Widget>[47Expanded(48//A widget that expands to fill the available space in the parent49child: Container(50color: Colors.red,51height: 50.0,52child: const Center(child: Text('Expanded Widget 1')),53),54),55Expanded(56child: Container(57color: Colors.green,58height: 50.0,59child: const Center(child: Text('Expanded Widget 2')),60),61),62],63),64],65),66),67);68}69}
Key Takeaways
- Column and Row widgets help structure your layout by arranging widgets vertically and horizontally.
- Container can be used for styling, padding, margins, and applying backgrounds.
- Wrap is handy for responsive layouts, where widgets should flow into new lines when the space is insufficient.
- Expanded is used to allocate the available space among children in a Row or Column.
By combining these widgets, you can create complex and responsive layouts in Flutter with ease.
©2024 Codeblockz
Privacy Policy