Flutter for循环生成小部件列表

时间:2019-07-09 07:07:08

标签: flutter dart

我有这样的代码,但是我希望它遍历整数数组以显示动态数量的子代:

return Container(
  child: Column(
    children: <Widget>[
      Center(
        child: Text(text[0].toString(),
            textAlign: TextAlign.center),
      ),
      Center(
        child: Text(text[1].toString(),
            textAlign: TextAlign.center),
      ),
    ],
  ),
)

此处text变量是一个整数列表,在此将其转换为字符串。我尝试添加一个函数来遍历数组并显示“子级”,但遇到类型错误。由于我是Dart和Flutter的新手,所以不确定该怎么做。

6 个答案:

答案 0 :(得分:7)

您可以在这里尝试.map方法,

class Example extends StatelessWidget {

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

  @override
  Widget build(BuildContext context) {
    return
      Container(
        child: Column(
            children: exampleList.map((i) => new Text(i.toString())).toList()
        ),
      );
  }
}

如果列表中有对象,该方法将派上用场。还要使用 .map()方法,最后必须使用 .toList()

答案 1 :(得分:2)

您可以尝试以下方法:

@override
  Widget build(BuildContext context) {
    List<int> text = [1,2,3,4];
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: Column(
          children: [
            for ( var i in text ) Text(i.toString())
          ],
        ),
      ),
    );

请注意,此命令是在dart版本2.3更新中添加的。您可以了解this article

中的一些最佳更改

dart 2.3之前提供的另一种方法是:

@override
  Widget build(BuildContext context) {
    List<int> text = [1,2,3,4];
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: Column(
          children: List.generate(text.length,(index){
            return Text(text[index].toString());
          }),
        ),
      ),
    );

答案 2 :(得分:1)

执行此操作的最佳方法是利用List.map()

那样,您不必启用“控制流收集”

 Container(
        child: Column(
            children: myList.map((e) => new Text(e)).toList(),
          ),
   );

答案 3 :(得分:1)

DartPad:Code Snippet

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(context) => MaterialApp(
    home: HomePage()
  );
}


class HomePage extends StatelessWidget {
  @override
  Widget build(context) => Scaffold(
    appBar: AppBar(title: Text("test")),
    body: SafeArea(
        child:Center(
          child:
          Row(
            children: [
              Container(
                width: MediaQuery.of(context).size.width-200.0,
                child: Content()
              )
            ]
          )
        )
    )
  );
}

class Content extends StatelessWidget {
  final List<String> elements = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "A Million Billion Trillion", "A much, much longer text that will still fit"];
  @override
  Widget build(context) => GridView.builder(
    itemCount: elements.length,
    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
      maxCrossAxisExtent: 130.0,
      crossAxisSpacing: 20.0,
      mainAxisSpacing: 20.0,
    ),
    itemBuilder: (context, i) => Card(
      child: Center(
        child: Padding(
          padding: EdgeInsets.all(8.0), child: Text(elements[i])
        )
      )
    )
  );
}

答案 4 :(得分:1)

您可以使用字符串列表的map方法。

 Widget _getListWidgets(List<String> yourList){
    return Row(children: yourList.map((i) => Text(i)).toList());
  }

当列表具有复杂的对象时:

Widget _getListWidgets( List<YourObject> lstItens) {
  return Row(children: lstItens.map((i) => Text(i.name)).toList());
}

答案 5 :(得分:1)

假设您想在 Column 小部件中循环一些小部件(例如 Text()),您可以在 children 属性中添加一个循环。请参阅下面的示例:

def main():
    q = queue.Queue()
    threads = [threading.Thread(target=create_url_threaded, args=(project_id_number,string_id, q)) for i in range(5) ]  #5 is for testing
    for th in threads:
        th.daemon = True
        th.start()

    result1 = q.get()
    result2 = q.get()