Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create function which return array of widgets

Tags:

flutter

I have to create a function which returns array of widgets, like this:

new GridView.count(crossAxisCount: _column,children: getRandomWidgetArray(),

Example function like this:-

Widget[] getRandomWidgetArray()
    {
      Widget[] gameCells;
      for(i=0;i<5;i++)
       {
          gameCells.add(new MyCellWidget(i));
       }
      return gameCells;
    }

Above code is giving this error:

enter image description here

I know how to do it without function:

children: < Widget >[ new MyCellWidget(0),
                      new MyCellWidget(1),]

But I have to make it dynamic with function as values will change in future, above code is just prototype. Flutter examples are very few.

like image 602
pallav bohara Avatar asked May 15 '18 10:05

pallav bohara


People also ask

How do you create an array of widgets in flutter?

How do you create an array in Flutter? A new array can be created by using the literal constructor [] : import 'dart:convert'; void main() { var arr = ['a','b','c','d','e']; print(arr); import 'dart:convert'; void main() { var arr = new List(5);// creates an empty array of length 5.


3 Answers

Array types are List<Type> in Dart:

List<Widget> getRandomWidgetArray()

[] can only be used as literal value to create a new list value, not for type declaration.

like image 110
Günter Zöchbauer Avatar answered Nov 14 '22 21:11

Günter Zöchbauer


At this time, the following code is deprecated:

List <Widget> gameCells = List<Widget>();

Use the following instead:

List <Widget> gameCells = <Widget>[];

The first code will work anyway, but you will have a warning.

like image 4
Manuel Diez Avatar answered Nov 14 '22 21:11

Manuel Diez


List<Widget> getRandomWidgetArray(){

  List <Widget> gameCells = List<Widget>();
  for(i=0;i<5;i++)
   {
      gameCells.add(new MyCellWidget(i));
   }
  return gameCells;
}

This is the correct way of initializing List, adding elements and returning Widget list.

like image 3
Aman Kumar Avatar answered Nov 14 '22 23:11

Aman Kumar