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:
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With