Flutter中通过循环渲染组件

class ContactsState extends State<Contacts>{

List formList;
initState() {
super.initState();
formList = [
{"icon": Icon(Icons.alarm),"title": '车牌号'},
{"icon": Icon(Icons.album),"title": '所有人'},
{"icon": Icon(Icons.archive),"title": '号牌颜色'},
];
}
Widget buildGrid() {
List<Widget> tiles = [];//先建一个数组用于存放循环生成的widget
Widget content; //单独一个widget组件,用于返回需要生成的内容widget
for(var item in formList) {
tiles.add(
new Row(
children: <Widget>[
new Icon(Icons.alarm),
new Text(item['title']),
]
)
);
}
content = new Column(
children: tiles //重点在这里,因为用编辑器写Column生成的children后面会跟一个<Widget>[],
//此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误,把<Widget>[]删了就可以了
);
return content;
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('循环渲染组件案例'),
),
body: new Center(
child: buildGrid(),
)
);
}

}

 

 

第二个例子

 

import 'package:flutter/material.dart';

class Tabledemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _Tabledemo();
  }
}

class _Tabledemo extends State<Tabledemo> {
  List demoList = [
    {
      "A": "list1",
      "B": "list2",
      "C": "list3",
    },
    {
      "A": "list1",
      "B": "list2",
      "C": "list3",
    },
    {
      "A": "list1",
      "B": "list2",
      "C": "list3",
    },
    {
      "A": "list1",
      "B": "list2",
      "C": "list3",
    },
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Table Demo'),
        centerTitle: true,
      ),
      body: Container(
          child: ListView(
        children: <Widget>[
          Table(
            border: TableBorder.all(width: 1.0, color: Colors.black12),
            children: _tableRowList(),
          ),
        ],
      )),
    );
  }

  _tableRowList() {
    var count = demoList.length;
    dynamic content;
    List<TableRow> Tlist = <TableRow>[
      TableRow(
        children: [
          Center(child: Text('标题A')),
          Center(child: Text('标题B')),
          Center(child: Text('标题C')),
        ],
      ),
    ];
    for (var i = 0; i < count; i++) {
      content = TableRow(
        children: [
          Center(child: Text(demoList[i]['A'].toString())),
          Center(child: Text(demoList[i]['B'].toString())),
          Center(child: Text(demoList[i]['C'].toString())),
        ],
      );
      Tlist.add(content);
    }
    return Tlist;
  }
}
posted @ 2020-05-21 19:07  zxh91989  阅读(165)  评论(0编辑  收藏  举报