如何在 flutter 中向 StatefulWidget 添加方法?

How can I add method to StatefulWidget in flutter?

我想调用这个方法但是不能。我的目的是 从文本变量中获取字符串 使用字符串中的单词制作列表 显示列表。 我希望通过这个来完成它。有没有其他方法或者我可以这样做?

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),
        ),
      ),
    );
  }
}

你应该移动“List wordlist = breakText();”进入 initState() 或 build() 方法。

1-定义列表:

List wordlist ;

2-初始化:

 @override
  void initState(){
wordlist = breakText();
}

调用时需要初始化数据_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),
        ),
      ),
    );
  }
}