Layout trong Flutter – Làm chủ Row, Column, Container, Expanded


Mục tiêu:

  • Hiểu cách sắp xếp widget theo chiều ngang, dọc, hoặc chồng lớp.
  • Sử dụng RowColumnContainerExpandedPaddingSizedBox.
  • Tạo layout responsive đơn giản.

1. Flutter layout hoạt động thế nào?

Flutter dùng cây widget (widget tree). Một layout được xây từ nhiều widget lồng nhau. Không có HTML hay CSS – mọi thứ là Dart code.


2. Column – xếp dọc

Column(
  children: [
    Text('Tiêu đề'),
    SizedBox(height: 20),
    Text('Mô tả ngắn'),
  ],
)

Thuộc tính quan trọng:

  • mainAxisAlignment: căn chỉnh theo trục dọc
  • crossAxisAlignment: căn chỉnh ngang

3. Row – xếp ngang

Row(
  children: [
    Icon(Icons.star),
    SizedBox(width: 10),
    Text('Đánh giá'),
  ],
)

Dùng Row khi muốn các widget nằm cạnh nhau theo chiều ngang.


4. Container – xây khối giao diện

Container(
  padding: EdgeInsets.all(16),
  margin: EdgeInsets.symmetric(horizontal: 20),
  color: Colors.grey[200],
  child: Text('Nội dung trong container'),
)

Container có thể dùng để tạo khối, định kích thước, căn lề, thêm màu nền, viền.


5. Expanded – chia tỉ lệ không gian

Row(
  children: [
    Expanded(child: Container(color: Colors.red)),
    Expanded(child: Container(color: Colors.green)),
    Expanded(child: Container(color: Colors.blue)),
  ],
)

Expanded cho phép chia đều hoặc theo tỉ lệ không gian.


6. SizedBox – khoảng trắng

SizedBox(height: 20) // tạo khoảng cách dọc
SizedBox(width: 10)  // tạo khoảng cách ngang

7. Padding – căn lề bên trong

Padding(
  padding: EdgeInsets.all(16),
  child: Text('Căn lề toàn bộ 16px'),
)

8. Ví dụ thực hành: card sản phẩm

Container(
  padding: EdgeInsets.all(16),
  margin: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(10),
    boxShadow: [
      BoxShadow(color: Colors.grey, blurRadius: 5, offset: Offset(0, 2))
    ],
  ),
  child: Row(
    children: [
      Icon(Icons.shopping_cart, size: 40),
      SizedBox(width: 20),
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text('Sản phẩm A', style: TextStyle(fontWeight: FontWeight.bold)),
          Text('Giá: 100.000đ'),
        ],
      ),
    ],
  ),
)

9. Bài tập thực hành

  • Tạo giao diện danh sách 3 sản phẩm.
  • Mỗi sản phẩm là 1 Row gồm icon, tên, giá.
  • Dùng ContainerSizedBoxPaddingColumnRow.

Tổng kết

  • Layout trong Flutter xây dựng từ widget lồng nhau.
  • RowColumn xác định hướng sắp xếp.
  • ContainerPaddingSizedBox giúp căn chỉnh, tạo khối.
  • Expanded giúp chia tỉ lệ linh hoạt.

Bài tiếp theo: Form, nhập liệu, xử lý sự kiện với TextFieldFormController.