简体   繁体   English

Flutter for循环生成小部件列表

[英]Flutter for loop to generate list of widgets

I have code like this but I want it to iterate over an integer array to display a dynamic amount of children:我有这样的代码,但我希望它遍历 integer 数组以显示动态数量的子项:

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

Where the text variable is a list of integers converter to string here.这里的text变量是一个转换为字符串的整数列表。 I tried adding a function to iterate through the array and display the 'children' but was getting a type error.我尝试添加 function 以遍历数组并显示“子项”,但出现类型错误。 Not sure how to do it since I'm new to Dart and Flutter.不知道该怎么做,因为我是 Dart 和 Flutter 的新手。

You can try this :你可以试试这个:

@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())
          ],
        ),
      ),
    );

Note that this was added with the updated of dart to version 2.3.请注意,这是随着 dart 更新到 2.3 版而添加的。 You can read about some of the best changes in this article您可以阅读本文中的一些最佳更改

Another method that was provided before dart 2.3 is this:在 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());
          }),
        ),
      ),
    );

You can try .map Method here,你可以在这里尝试 .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()
        ),
      );
  }
}

Thie method will come in handy if you have objects inside your list.如果你的列表中有对象,这个方法会派上用场。 Also with the .map() method .toList() must be used at the end.还必须在最后使用.map()方法.toList()

Assuming you want to loop some widgets (eg Text()) in the Column widget, you can add a loop inside the children property.假设您想在 Column 小部件中循环一些小部件(例如 Text()),您可以在 children 属性中添加一个循环。 See a sample below:请参阅下面的示例:

Column(
   children: <Widget>[
                   for (int i=0; i<3; i++)
                      Text("Hello" + i)
                     ],
        )

The best way to do this is to make use of the List.map()最好的方法是使用List.map()

That way you do not have to enable 'control-flow-collections'这样您就不必启用“控制流集合”

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

DartPad: Code Snippet DartPad:代码片段

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])
        )
      )
    )
  );
}

And also you do it like this way你也这样做

return new ListView(
  children: new List.generate(10, (index) => new ListTile()),
);

You could use the map method of your list of Strings.您可以使用字符串列表的 map 方法。

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

When your List have a complex Object:当你的 List 有一个复杂的对象时:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM