[Flutter] List.generate

keemeesuu·2023년 2월 26일
0

Flutter

목록 보기
5/5

List를 생성하며 index마다 값을 줄 수 있다.

import 'package:flutter/material.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
      ),
      home: MyHomePage(),
    );
  }
}
 
class MyHomePage extends StatelessWidget {
  final List<String> items = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
 
  
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 3,  // 열 개수
        children: List<Widget>.generate(items.length, (idx) {
          return Container(
            color: Colors.![](https://velog.velcdn.com/images/keemeesuu/post/b92aa255-d89a-4337-bef0-963556069057/image.png)
,
            padding: const EdgeInsets.all(40),
            margin: const EdgeInsets.all(8),
            child: Text(
                items[idx],
                style: TextStyle(fontSize: 30),
                textAlign: TextAlign.center,
            ),
          );
        }).toList()
      )
    );
  }
}

List.generate() 생성자 사용

응용예제

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final List<String> items = List.generate(9, (index) => "${index}");

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: GridView.count(
        crossAxisCount: 3, // 열 개수
        children: [
          for( var item in items )Container(
            color: Colors.blue,
            padding: const EdgeInsets.all(40),
            margin: const EdgeInsets.all(8),
            child: Text(
              "${item}",
              style: TextStyle(fontSize: 30),
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }
}
profile
개발관련 정리하고 기록하는 블로그 🦦

0개의 댓글