flutter中通過循環渲染組件


直接貼代碼:

 1 import 'package:flutter/material.dart';
 2 
 3 class Example extends StatefulWidget {
 4     @override
 5     _ExampleState createState() => _ExampleState();
 6 }
 7 
 8 class _ExampleState extends State<ExamplePage> {
 9     List formList;
10     initState() {
11       super.initState();
12         formList = [
13             {"title": '車牌號'},
14             {"title": '所有人'},
15             {"title": '號牌顏色'},
16         ];
17     }
18      Widget buildGrid() {
19             List<Widget> tiles = [];//先建一個數組用於存放循環生成的widget
20             Widget content; //單獨一個widget組件,用於返回需要生成的內容widget
21             for(var item in formList) {
22                 tiles.add(
23                     new Row(
24                        children: <Widget>[
25                          new Text(item['title'])
26                        ]
27                     )
28                 );
29             }
30             content = new Column(
31                 children: tiles //重點在這里,因為用編輯器寫Column生成的children后面會跟一個<Widget>[],
32                 //此時如果我們直接把生成的tiles放在<Widget>[]中是會報一個類型不匹配的錯誤,把<Widget>[]刪了就可以了
33             );
34             return content;
35         }
36       Widget ExampleWidget = buildGrid();
37     @override
38     Widget build(BuildContext context) {
39         return Scaffold(
40             key: scaffoldKey,
41             appBar: AppBar(
42                 title: Text('循環渲染組件案例'),
43             ),
44             body: new Center(
45                 child: ExampleWidget
46             )
47         );
48     }
49 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM