Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass List of Widgets in children property of another Widget?

Tags:

flutter

dart

Taking the following function as example:

List<Widget> getListFiles() {
    List<Widget> list = [
        Container(),
        Container(),
        Container(),
    ];

    return list;
}

How to insert into a children param?

Column(
    children: <Widget>
    [
        Text(),
        Text(),
        getListFiles(), <---
        Text(),
    ]
)
like image 305
Linesofcode Avatar asked Mar 21 '19 17:03

Linesofcode


1 Answers

Update

Now Dart has spread operator with the version 2.3.

[
  ...anotherList
  item1
]

Answer without Spread operator

I think you need to spread your list since you can't assign element type 'List' to the list type 'Widget'. Spread operator is a feature that wanted. You can follow the issue about it on here.

Meanwhile you can use generators and yield operator.

Column(
  children: List.unmodifiable(() sync* {
    yield Text();
    yield Text();
    yield* getListFiles();
    yield Text();
  }()),
);

Full code of the usage in widget.

import 'package:flutter/material.dart';

class App extends StatelessWidget {
  List<Widget> getListFiles() {
    List<Widget> list = [Text('hello'), Text('hello1'), Text('hello2')];

    return list;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stackoverflow'),
      ),
      body: Column(
        children: List.unmodifiable(() sync* {
          yield Text('a');
          yield Text('b');
          yield* getListFiles();
          yield Text('c');
        }()),
      ),
    );
  }
}
like image 174
mirkancal Avatar answered Oct 21 '22 16:10

mirkancal