Home Coding Bắt đầu với Flutter – Dogs App: ListView và Builder Methods

Bắt đầu với Flutter – Dogs App: ListView và Builder Methods

by Khanh Tran

Kết thúc bài trước, chúng ta mới tạo thành công Dog_card. Kết quả cuối cùng mà chúng ta hướng đến là hiển thị tất cả các Dog_card dưới dạng danh sách. Hôm nay chúng ta cùng tìm hiểu một trong những khái niệm quan trọng nhất trong Flutter UI là rendering UI lists. Cụ thể, bài hôm nay sẽ nói về ListView và Builder Methods
Builder methods về cơ bản sẽ tạo một widget một lần cho mỗi phần dữ liệu trong một Dart List.

DogList Class

Đầu tiên, tạo một tệp mới có tên dog_list.dart.

// dog_list.dart
import 'package:flutter/material.dart';
import 'dog_card.dart';
import 'dog_model.dart';
class DogList extends StatelessWidget {
  // Builder methods rely on a set of data, such as a list.
  final List<Dog> doggos;
  DogList(this.doggos);
  // First, make your build method like normal.
  // Instead of returning Widgets, return a method that returns widgets.
  // Don't forget to pass in the context!
  @override
  Widget build(BuildContext context) {
    return _buildList(context);
  }
  // A builder method almost always returns a ListView.
  // A ListView is a widget similar to Column or Row.
  // It knows whether it needs to be scrollable or not.
  // It has a constructor called builder, which it knows will
  // work with a List.
  ListView _buildList(context) {
    return ListView.builder(
      // Must have an item count equal to the number of items!
      itemCount: doggos.length,
      // A callback that will return a widget.
      itemBuilder: (context, int) {
        // In our case, a DogCard for each doggo.
        return DogCard(doggos[int]);
      },
    );
  }
}

Để sử dụng DogList, Thay thế DogCard trong file Main bằng DogList.

Đầu tiên, import DogList vào main.dart. Lưu ý rằng việc dog_card.dart không còn cần thiết nữa.

// main.dart
import 'package:flutter/material.dart';
import 'dog_list.dart';
import 'dog_model.dart';

Sau đó sửa build method trong _MyHomePageState:

// main.dart
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
      backgroundColor: Colors.black87,
    ),
    body: Container(
      // Remove the DogCard Widget.
      // Instead, use your new DogList Class,
      // Pass in the mock data from the list above.
      child: Center( // Changed code
        child: DogList(initialDoggos), // Changed code
      ),
    ),
  );
}

Và đây là kết quả:

Hình 1: ListView Dog_card

You may also like

Leave a Comment