0

Example 1 Can someone show me how to add this Example 1 to stateless or stateful widget in Flutter?

Joe Joe
  • 3
  • 3

1 Answers1

0

So you've come across the classic inability to use a variable you've just defined.

Here's the best solution:

Go ahead and define the variable in the class

class _MyHomePageState extends State<MyHomePage> {

  List<String> singleWord = "im so cool".split(" ");
  (...)

}

And then you can use that variable in any function. For example, the "initState" function is called once when the class is initiated, so we can put our usage of the function in that.

class _MyHomePageState extends State<MyHomePage> {

  List<String> singleWord = "im so cool".split(" ");
 
  @override
  void initState() {
    singleWord.forEach((e) => print(e));
    super.initState();
  }
 (...)

}

If you want to use the same function multiple times then just remove the @override and name the function something that makes sense. E.g. singleWordSplitPrint

However, please do NOT use the variable inside the build method as the build method is called way more than you think - especially when you're just starting out and your setState((){})'s aren't perfect!

Good luck!

Percent.twof
  • 186
  • 6
  • Thank you i got it now! By the way if you don't mind i have another problem which is i tried to display the output in flutter app and fail to do so, do you know how? – Joe Joe Apr 06 '22 at 04:44
  • @JoeJoe Could you give me a little more information on what exactly you tried to do? :) – Percent.twof Apr 06 '22 at 15:45