Flutter/Flutter 스파르타코딩클럽

ListView vs. ListView.builder / ListView.separated

Developer-Michelle 2023. 9. 28. 16:24

ListView 는 반복적으로 작성

ListView.builder() 이용하면 더 적은 코드로 itemCount 만큼 화면을 그릴 수 있다.

 

ListView 예제

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            Text('Hello ListView'),
            Text('Hello ListView'),
            Text('Hello ListView'),
            Text('Hello ListView'),
          ],
        ),
      ),
    );
  }
}

 

ListView.builder() 예제

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: ListView.builder(
          itemCount: 100, // 전체 아이템 개수
          itemBuilder: (context, index) {
            // index는 0 ~ 99까지 증가하며 itemCount만큼 호출됩니다.

            // Text 위젯을 반환합니다.
            return Text("$index");
          },
        ),
      ),
    );
  }
}

 

ListView.separated - 요소 사이사이에 줄 넣기 (ListView.builder에서 builder를 지우고 separated 로 수정 및 아래에 separatorBuilder 코드 추가)

 body: ListView.separated(
        itemCount: 10,
        itemBuilder: (context, index) {
          return Feed();
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
      ),

 

 

출처) 스파르타 코딩클럽 강의 중