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),
),
),
);
}
}
CodePudding user response:
You should move "List wordlist = breakText();" into initState() or build() method.
CodePudding user response:
1-Define List:
List wordlist ;
2-Initialize:
@override
void initState(){
wordlist = breakText();
}
CodePudding user response:
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),
),
),
);
}
}