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()
)
);
}
}
응용예제
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,
),
),
],
),
);
}
}