fluttersplitstatefulwidgetstatelesswidget

Flutter - How to put this string code into stateless widget or stateful widget?


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


Solution

  • 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!