mobile/flutter

flutter -카드형태로 List를 출력하기

예츄 2020. 12. 13. 20:43

메인 메소드 에서는 QuoteList()의 클래스를 실행한다.

void main() => runApp(MaterialApp(
  home: QuoteList(),
));

QuoteList() 클래스 안에는 <Quote> 타입의 List가 선언되어 있는데, 

Quote 클래스는 다음과 같다.

class Quote {

  String text;
  String author;

  Quote({this.text, this.author});

}

작가와, 글을 나타내기 위해 필드와 생성자를 선언해준다.

위의 생성자는 name parmeter 인 {}를 이용하여 선언했다.

이 경우라면, 후에 데이터를 넣는 경우 다음과 같이 작성할 수 있다.

name parameter를 쓰는 경우 순서가 바뀌어도 상관없다 -> Quote(author: ~, text: ~) 

Quote myquote = Quote(text:'this is txt',author:'me');

name parameter를 안쓰는 경우라면, 

  Quote(String text, String author){
    this.text = text;
    this.author = author;
  }

이렇게 생성자를 만들 수 있고, 이 경우, 다음과 같이 데이터를 넣을 수 있다.

Quote mine = Quote('this is text', 'me');

<Quote> 타입의 리스트에는 다음과 같은 3개의 데이터가 들어가 있고,

이를 카드 형태로 출력하기 위해 템플릿 위젯을 만든다. 이 템플릿 위젯은 Card 를 리턴한다. -->카드 형태 템플릿

한개의 데이터 - quote - 마다 다음과 같은 디자인의 카드가 생성된다

class QuoteList extends StatefulWidget { 
  @override
  _QuoteListState createState() => _QuoteListState();
}

class _QuoteListState extends State<QuoteList> {

  List<Quote> quotes = [
    Quote(author:'Oscar Wilde', text: 'Be yourself; everyone else is already taken'),
    Quote(author:'Oscar Wilde', text:  'I have nothing to declare except my genius'),
    Quote(author:'Oscar Wilde', text:  'The truth is rarely pure and never simple'),
  ];

    Widget quoteTemplate(quote){
    return Card(
      margin: EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0),
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch, // 템플렛 꽉 차게
          children: <Widget>[
            Text( // 인용구
              quote.text ,// '' 로 하는 거 아니니까 {}필요 없음
              style: TextStyle(
                fontSize: 18.0,
                color: Colors.grey[600],
              )
            ),
            SizedBox(height: 6.0),
            Text( // 작가
              quote.author,
              style: TextStyle(
                fontSize: 14.0,
                color:Colors.grey[600],
              )
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[200],
      appBar: AppBar(
        title: Text('Awesome Quotes'),
        centerTitle: true,
        backgroundColor: Colors.redAccent,
      ),
      body: Column(// 변수 property에 접근하려면 {} 감싸야함
        children: quotes.map((quote) => quoteTemplate(quote)).toList(), // cycle through the list of data
      ),
    );
  }
}

Widget build에는 언제나 그렇듯 Scaffold 위젯을 리턴하고 안에는 appBar, body를 설정하여 액션바와 바디에 인용구가 뜨도록 작성한다.

body에 Column 위젯을 넣고 세로로 출력되게 만들고,

데이터 리스트를 모두 돌 수 있도록 map함수를 이용한다.