build 메서드에서 위젯에 반복문을 사용할 일이 생겼음

해결

1. 인덱스가 필요 없을 경우

// 방법 1
class Example extends StatelessWidget {

  List <int> yourList =  [1,2,3,4];

  
  Widget build(BuildContext context) {
    return
        child: Column(
            children: yourList.map((element) => Text(yourElement.toString())).toList(),
      	);
  }
}

// 방법 2
class Example extends StatelessWidget {

  List <int> yourList =  [1,2,3,4];

  
  Widget build(BuildContext context) {
    return
        child: Column(
            children: for(yourElement in yourList) Text(yourElement.toString())
      	);
  }
}

2. 인덱스가 필요 있을 경우


  Widget build(BuildContext context) {
    List<int> yourList = [1,2,3,4];
    return 
        child: Column(
          children: List.generate(yourList.length,(index){
            return Text(yourList[index].toString());
          }
    	);

상황에 맞게 잘 사용하면 좋을 듯

profile
플러터로 개발하는걸 가장 선호합니다.

0개의 댓글