본문 바로가기

Flutter

Flutter - ListView

Listview

말 그대로 여러 가지 항목을 스크롤이 되는 list로 보여주는 위젯이다

 

생성 방법

1. Listview()

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        //physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.all(16),
        children: [
          ListTile(
            title: Text('title1'),
            subtitle: Text('subTitle1'),
            leading: Icon(Icons.assignment_sharp),
          ),
          Container(
            color: Colors.red,
            child: ListTile(
              title: Text('title1'),
              subtitle: Text('subTitle1'),
              leading: Icon(Icons.assignment_sharp),
            ),
          ),
          Container(
            color: Colors.blue,
            height: 50,
          )
        ],
      ),
    );
  }
}

Listview를 생성하고 childeren []에 listtile이나 container 등 위젯들을 명시적으로 넣어줘서 만드는 방법이다

listTile은 title, subtitle, leading 등 속성들이 있어서 listView의 자식들로 쓰기 좋다

사진을 보면 뭐가 title, subtitle, leading 인지 알 것이다

 

2. ListView.builder

itemCount를 통해서 listview의 항목이 몇 개인지 정해주고 itembuilder에서 return 받는 값을 itemcount만큼 뿌려줘서 규칙적으로 코드를 조금 더 간단하게 만들 수 있다

builder에서 itemcount에 해당하는 index를 받아준ㄴ다

그로 인해 index값에 대한 조건문도 만들어줄 수 있다

index%2==0? Colors.red:Colors.blue

->index가 짝수이면 색깔이 blue 아니면 red

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: 10,
        itemBuilder: (context,index){
          return Container(
            color: index%2==0?Colors.red:Colors.blue,
            child: ListTile(
              title: Text('listview.builder$index'),
              subtitle: Text('subTitle$index'),

            ),
          );
        },
      )
    );
  }
}

'Flutter' 카테고리의 다른 글

Flutter - Future, async, await  (0) 2022.01.03
Flutter - AVD(에뮬레이터) 설치  (0) 2022.01.03
Flutter - Container안에 이미지 넣기  (0) 2022.01.02
Flutter - Container  (0) 2022.01.02
Flutter - Column,Row  (0) 2022.01.02