Flutter

[Flutter] 목록 ListView, Builder & 버튼 기능 구현

hminor 2023. 7. 30. 20:54

목록 ListView, Builder & 버튼 기능 구현

  • 우선 좌측에 사진, 우측에 글이 있는 경우
    • 예를 들어 페이스북 또는 인스타, 카톡의 유저 목록을 구현할 때 사용하면 좋은 것으로 ListTile() 이라는 위젯이 있다.
    • ListTile()을 사용하면 Row를 하지 않아도 쉽게 레이아웃을 구현할 수 있는 장점이 있다.
    // 기존 숙제로 작성했던 코드
    body: ListView(
              children: [
                Row(
                  children: [
                    Icon(Icons.person, size: 50),
                    Text('홍길동', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w400),)
                  ],
                ),
                Row(
                  children: [
                    Icon(Icons.person, size: 50),
                    Text('홍길동', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w400),)
                  ],
                ),
                Row(
                  children: [
                    Icon(Icons.person, size: 50),
                    Text('홍길동', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w400),)
                  ],
                ),
              ],
            ),
    
    // ListTile() 을 사용한 코드
    body: ListView(
              children: [
                ListTile(
                  leading: Icon(Icons.person, size: 50),
                  title: Text('홍길동', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w400),)
                ),
                ListTile(
                    leading: Icon(Icons.person, size: 50),
                    title: Text('홍길동', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w400),)
                ),
                ListTile(
                    leading: Icon(Icons.person, size: 50),
                    title: Text('홍길동', style: TextStyle(fontSize: 20, fontWeight: FontWeight.w400),)
                ),
              ],
            ),
    
  • 여기서 저런 ListTile() 이 100개, 1000개로 엄청나게 많을 경우에 사용할 수 있는 반복문과 같은 것으로 ListView.Builder()가 있다.
    • ListView.Builder() 안에는 두 개의 파라미터가 있다
      • itemCount: 반복 횟수
      • itemBuilder: 함수
        • itemBuilder의 파라미터에도 두 개의 값이 꼭 들어가야 에러가 발생하지 않는다.
        • 첫 번째는 context로 c를 보통 기입하고
        • 두 번째는 for 문의 i로 i를 기입한다고 한다.
    • 그리고 세미 콜로를 작성하지 않으면 에러가 발생하는 것도 기억하기!
    body: ListView.builder(
                itemCount: 3,
                itemBuilder: (c,i){
                  return ListTile(
                    leading: Icon(Icons.person_pin),
                    title: Text('홍길동'),
                  );
                }
            ),
    
    • 그래서 i는 횟수가 출력 되기에 확인해보려면
      • Text는 문자만 출력할 수 있기에 i.toString()으로 기입을 하면 0부터 2까지 출력하는 것을 확인할 수 있다.
    body: ListView.builder(
                itemCount: 3,
                itemBuilder: (c,i){
                  return ListTile(
                    leading: Icon(Icons.person_pin),
                    title: Text(i.toString()),
                  );
                }
            ),
    
  • 그리고 return 전에 출력을 해보고 싶다면 Python처럼 print()를 사용하면 궁금한 변수를 콘솔창에서 확인할 수 있다.
  • 버튼에 기능 구현하기
    • 버튼에 기능을 구현하려면 floatingActionButton 속성을 사용하면 된다.
      • 마찬가지로 버튼이기에 child와 onPressed 두 개를 필수로 기입해줘야 하고
      • onPressed에는 역시 함수를 작성해주면 된다.
      • 그래서 상단에 a라는 변수에 1을 넣어주고 버튼을 클릭할 때마다 1 증가된 a를 콘솔창에서 확인할 수 있다.
    class MyApp extends StatelessWidget {
      MyApp({super.key});
    
      var a = 1;
    
      @override
      Widget build(BuildContext context) {
    
        return MaterialApp(
          home: Scaffold(
            floatingActionButton: FloatingActionButton(
              child: Text('버튼'),
              onPressed: (){
                a++;
                print(a);
              },
            ),
            appBar: AppBar(),
            body: ListView.builder(
                itemCount: 3,
                itemBuilder: (c,i){
                  return ListTile(
                    leading: Icon(Icons.person_pin),
                    title: Text(i.toString()),
                  );
                }
            ),
            bottomNavigationBar: BottomAppBar(),
          ),
        );
      }
    }