코드

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

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

class HomePage extends StatelessWidget {
  const HomePage({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          fourContainers(),
          fourContainers(),
          fourContainers(),
          fourContainers(),
        ],
      ),
    );
  }

  Padding fourContainers() {
    return Padding(
      padding: EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
          SizedBox(width: 8),
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
          SizedBox(width: 8),
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
          SizedBox(width: 8),
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
        ],
      ),
    );
  }
}

 

결과

ListView 내에서 fourContainers라는 메서드를 네 번 호출해서 이미지와 같은 레이아웃을 그리고 있다. 

현재는 메서드를 4번 호출하기 때문에 위와 같이 작성해도 문제가 없지만, 호출 횟수가 많아지면 코드의 가독성이 떨어지고 유지보수가 어려워진다.

 

 

https://devlogmj.tistory.com/15

 

[Dart] .generate와 .filled 사용하여 리스트 만들기

.generate 주어진 길이만큼 리스트를 생성하고, 각 요소에 대해 반복적인 패턴의 값을 할당하는 데 사용한다. List.generate() 문법List.generate(length, (index) => expression); length - 생성할 리스트의 길이index

devlogmj.tistory.com

이전에 정리한 .generate 함수를 사용하여 반복되는 메서드 호출을 깔끔하게 구현할 수 있다.

 

 

만약 fourContainers를 20번 반복해야 한다면?

 

기존 코드

몇 번 반복되는지 한 눈에 알아볼 수 없음

 

 

.generate로 개선한 코드

generate 함수 내 인자를 통해 20번 반복된다는 것을 알아볼 수 있다. 

 

또한, generate 함수의 특성상 규칙을 가진 리스트 요소를 간단하게 생성할 수도 있다.

 

예시

인덱스를 사용하여 줄마다 번호를 부여했다.

 

 

사용 코드

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

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

class HomePage extends StatelessWidget {
  const HomePage({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          ...List.generate(20, (index) {
            index = index + 1; // index를 1부터 시작하도록 처리
            return fourContainers(index);
          }),
        ],
      ),
    );
  }

  Padding fourContainers(index) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(width: 50, height: 50, child: Text('$index')),

          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
          SizedBox(width: 8),
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
          SizedBox(width: 8),
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
          SizedBox(width: 8),
          Container(
            width: 50,
            height: 50,
            decoration: BoxDecoration(color: Colors.amber),
          ),
        ],
      ),
    );
  }
}

 

+ Recent posts