I'm very new to Flutter and I'll be grateful for any help. I've created a two dimensional List using List.generate and then I want to iterate through the List and change the first value in each row. I've done this in Dartpad and it works as expected. I cant get it to work in my Flutter app.
Here's the code that works in Dartpad:
List myList = List.generate(12, (i) => List<String>.filled(12, '-'), growable: false);
for (int i = 0; i < myList.length; i ) {
int s = i 1;
myList[i][0] = "List $s";
}
But when I use it in Flutter as follows:
class _MyPage extends State<MyPage> {
List myList =
List.generate(12, (i) => List<String>.filled(12, '-'), growable: false);
for (int i = 0; i < myList.length; i ) {
int s = i 1;
myList[i][0] = "List $s";
}
Flutter errors on the **for **loop stating:
Expected a class member.
Try placing this code inside a class member.
Removing the for loop leave the initial generated list, myList filled with '-' but I want to change the first item in each row to 'List x' by using a for loop.
For the life of me I cant sort this out. Please help.
CodePudding user response:
You can declare in a class
only members that belong to it like variables, methods, getters...
adding directly a for
loop is wrong and can't be accepted, however, in the other hand you can declare a function
that executes the for
loop code, like this:
class _MyPage extends State<MyPage> {
List myList =
List.generate(12, (i) => List<String>.filled(12, '-'), growable: false);
executeLoop() {
for (int i = 0; i < myList.length; i ) {
int s = i 1;
myList[i][0] = "List $s";
}
}
now we have a class member which is the executeLoop
, and now you can call that function to execute it.
the StateFulWidget
have a lifecycle method called initState()
, which is called automatically when the widget is added to the tree widget, so you can do like this:
class _MyPage extends State<MyPage> {
List myList =List.generate(12, (i) => List<String>.filled(12, '-'), growable: false);
executeLoop() {
for (int i = 0; i < myList.length; i ) {
int s = i 1;
myList[i][0] = "List $s";
}
@override
initState() {
super.initState();
executeLoop();
}
}
and now the executeLoop
will be executed, which means that your for
loop will be executed now as you expect.
Hope this helps you!