How do I use collection for-loops in Flutter?

后端 未结 2 1415
野性不改
野性不改 2021-01-20 02:38

I am trying to add widgets in a SliverList using a for-loop.
But I get the following error:

error: The element type \'Se

相关标签:
2条回答
  • 2021-01-20 03:14

    The problem here is that the collection for operator does not take curly braces ({}). i.e. they do not work with them as you can tell.
    Curly braces are used for Set and Map literals. If you add a colon behind an entry, it becomes a Map literal, e.g. { 'flavor': 'sweet' }. However, if you just use curly braces, it creates a Set. Usually this does not affect for-loops because curly braces are used as regular flow control.

    Anyways, to fix the issue you simply need to remove your curly braces:

    for(var i = 0; i < 5; i++) EachBusInfoBodyWidget(Colors.green)
    
    0 讨论(0)
  • 2021-01-20 03:19

    Change your build method as follows:

    @override
    Widget build(BuildContext context) {
    //insert
    List<Widget> widgets = List<Widget>();          
    
    for(var i=0;i<5;i++){
      widgets.add(EachBusInfoBodyWidget(Colors.green));                  
    }
    //end insert
    return Scaffold(
    

    And also change your CustomScrollView:

         child: CustomScrollView(
          slivers:
          <Widget>[
            SliverList(
              delegate: SliverChildListDelegate(
               //insert
                widgets
               //end insert
              ),
            ),
          ],
        ),
    
    0 讨论(0)
提交回复
热议问题