Flutter:从另一个类调用SetState()
我试图制作一个简单的图像,当按下按钮时该图像会出现或消失。该按钮位于图像的单独类中,因此在Flutter中,这会引起问题的严重困扰。
我已经阅读了许多论坛,并尝试了所有提出的解决方案,但没有一个对我有用。
我正在尝试做的是:
class SinglePlayerMode extends StatefulWidget { @override
SinglePlayerModeParentState createState() => SinglePlayerModeParentState();
}
class SinglePlayerModeParentState extends State<SinglePlayerMode> {\
bool coinVisible = false;
toggleCoin() {
setState(() {
coinVisible = !coinVisible;
});
}
Widget topMenuRow() {
return Stack(
children: [
Column(
children: [
coinVisible == true ?
Padding(
padding: EdgeInsets.all(50),
child: Container(
height: 60,
width: 60,
color: Colors.blueGrey[0],
decoration: BoxDecoration(
color: Colors.blueAccent,
image: DecorationImage(
image: ExactAssetImage('lib/images/coin_head.jpg'),
fit: BoxFit.cover,
),
),
),
) : Container(
height: 60,
width: 60,
color: Colors.black,
),
],
),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
child: ListView(
padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
children: [
topMenuRow(),
SizedBox(height: 40),
],
),
),
);
}
这是我想在coinVisible上触发SetState()的单独类,它来自:
class dropDownMenu extends StatefulWidget { @override _dropDownMenuState createState() => _dropDownMenuState();
}
class _dropDownMenuState extends State<dropDownMenu> {
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget> [
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Container(
child: Opacity(
opacity: 0.0,
child: FloatingActionButton(
heroTag: null,
onPressed: (){
//SOMEHOW CALL SetState() ON coinVisble HERE!
},
),
),
);
}
}
但是我尝试过的所有方法都没有起作用,而且我已经浪费了很多时间。
回答:
很简单,您需要将SinglePlayMode :: toggleCoin函数作为回调发送到dropDownMenu类。
class dropDownMenu extends StatefulWidget { final _callback; // callback reference holder
//you will pass the callback here in constructor
dropDownMenu( {@required void toggleCoinCallback() } ) :
_callback = toggleCoinCallback;
@override
_dropDownMenuState createState() => _dropDownMenuState();
}
class _dropDownMenuState extends State<dropDownMenu> {
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget> [
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Container(
child: Opacity(
opacity: 0.0,
child: FloatingActionButton(
heroTag: null,
onPressed: (){
widget?._callback(); // callback calling
},
),
),
);
}
}
然后,当您在SinglePlayerMode类中创建dropDownMenu类实例时,您将执行
dropDownMenu( toggleCoinCallback: toogleCoin,
);
以上是 Flutter:从另一个类调用SetState() 的全部内容, 来源链接: utcz.com/qa/428955.html