How to solve: How can I add method to StatefulWidget in flutter?

Question

Asked by masfiq r on November 26, 2021 (source).

I want to call this method but can not. My purpose is to take the string from text variable make a list using the word from string show the list. I was hoping to done it by this. Is there any other way or can I do it in this way?

class SecondRoute extends StatefulWidget {
  String text;
  //const SecondRoute({Key? key}) : super(key: key);
  SecondRoute({Key? key, required this.text}) : super(key: key);

  @override
  _SecondRouteState createState() => _SecondRouteState();


}

class _SecondRouteState extends State<SecondRoute> {
  String newT ="";
  

  List breakText(){
   newT = widget.text;
    var x = newT.split(" ");
    print(x);
    bool res = x.remove("");
    while(res == true){
      res = x.remove("");
    }
    print(x);
    return x;

  }
  List wordlist = breakText();// can not call this method
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: Center(
        child: Text(
          "hhhh",
          // text,
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

Answer

Question answered by Jahidul I (source).

you need to initialize your data when call _SecondRouteState

class SecondRoute extends StatefulWidget {
  String text;
  //const SecondRoute({Key? key}) : super(key: key);
  SecondRoute({Key? key, required this.text}) : super(key: key);

  @override
  _SecondRouteState createState() => _SecondRouteState();


}

class _SecondRouteState extends State<SecondRoute> {
  String newT ="";
  

  List breakText(){
   newT = widget.text;
    var x = newT.split(" ");
    print(x);
    bool res = x.remove("");
    while(res == true){
      res = x.remove("");
    }
    print(x);
    return x;

  }
  List wordlist; // declare your list
  @override
  void initState() {
    super.initState();
    wordlist = breakText(); // initialize from here

  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Route"),
      ),
      body: Center(
        child: Text(
          "hhhh",
          // text,
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}

DART FLUTTER INHERITANCE PARENT PARENT-CHILD
SHARE: