1

I´m new to flutter and got a question that makes me crazy for 2 days :) I want to use a parameter(name1) in a list, but can´t figure out what went wrong:


  List<Widget> player = [Text(name1)];
  String name1 = 'Max';

  @override
  Widget build(BuildContext context) {
    return Container(
      child: player[0],
    );
  }
}

Error: Can't access 'this' in a field initializer to read 'name1'

This is a simplified version, but includes the problem.

Der Finn
  • 17
  • 7

1 Answers1

0

You cannot use a just initialized variable to initialize another variable. You can call the variable inside a method. For example if is a StatefulWidget, you can fill the list inside the initState method.

  List<Widget> player = [];
  String name1 = 'Max';
  
  @override
  void initState() {
    player.add(Text(name1));
    super.initState();
  }

Or you can initialize the list with all the widgets already:

List<Widget> player = [Text('name1'),Text('name2')];
Jorge Vieira
  • 2,784
  • 3
  • 24
  • 34
  • Thanks for the answer. That helps me with understanding the problem. Maybe you know a solution to a problem that comes along with your answer: I have a stless Wigdet in a list and want to pass data to it. List player = [ custom_widget(name: name1 ) ]; name is the parameter I use in the custom_widget, name1 is the value that is passed. Since I can´t do it as I planed to do, maybe you know another way of doing it? – Der Finn May 01 '21 at 13:13
  • Well, you can do this inside a method, like i said, just create a method to initialize the list inside it, then call where you want. Maybe if you show more code and where is the error we can find a solution for it. – Jorge Vieira May 01 '21 at 13:46
  • 1
    Hey, I found a solution with initState. Without your answer I´d still sit here bumping my head against the wall. Thanks so much! – Der Finn May 01 '21 at 13:56