使用Flutter并尝试将Widget移出另一个类以使其保持模块化。 问题是内部Widget中有一个setState。但是,当我将其移到另一个类时,它是无效的,因为它不是有状态的。最初考虑传递一个Function并将其替换为setState函数本身,但这似乎不起作用。我该如何解决?
目前运作良好的方法。我计划将所有内容从第6行(子代:Center)移到另一个类,因为这将通过PageView重复进行。将此页面滑到下一页,每个页面看起来都一样,只是文本改变了。
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.tealAccent,
body: SafeArea(
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"Did you hear about the claustrophobic astronaut?",
style: TextStyle(
fontSize: 20,
),
),
Text(
"He just needed a little space.",
style: TextStyle(
fontSize: 20,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
GestureDetector(
child: Icon(heartStatus),
onTap: () {
setState(() {
if (heartStatus == FontAwesomeIcons.heart) {
heartStatus = FontAwesomeIcons.solidHeart;
} else {
heartStatus = FontAwesomeIcons.heart;
}
});
},
),
GestureDetector(
child: Icon(FontAwesomeIcons.shareAlt),
onTap: (){
print('shared');
},
),
],
),
],
),
),
),
),
);
}
这是在将其移至另一个花药类别之后,因为设置状态在此处无效的原因。在此处传递函数会引发错误->不必要的语句
Widget getPageData(Function function){
IconData heartStatus = FontAwesomeIcons.heart;
return Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"Did you hear about the claustrophobic astronaut?",
style: TextStyle(
fontSize: 20,
),
),
Text(
"He just needed a little space.",
style: TextStyle(
fontSize: 20,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
GestureDetector(
child: Icon(heartStatus),
onTap: () {
setState(() {
//tried passing in function here
if (heartStatus == FontAwesomeIcons.heart) {
heartStatus = FontAwesomeIcons.solidHeart;
} else {
heartStatus = FontAwesomeIcons.heart;
}
});
},
),
GestureDetector(
child: Icon(FontAwesomeIcons.shareAlt),
onTap: (){
print('shared');
},
),
],
),
],
),
),
);
}
答案 0 :(得分:0)
您可以转动function
:
Widget getPageData(Function function){...}
致Customised Widget
class CustomizeWidget extend StatefulWidget{
}
class _CustomizeWidgetState extend State<StatefulWidget>{
/// in the build function, you can call setState
}