Bis*_*ret 5 widget setstate flutter
我正在尝试制作一个在按下按钮时出现或消失的简单图像。这个按钮位于图像的一个单独的类中,所以在 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),
],
),
),
);
}
Run Code Online (Sandbox Code Playgroud)
这是我想在 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!
},
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
但是我尝试过的一切都不起作用,而且我已经失去了几个小时。
很简单,您需要将 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
},
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当您在 SinglePlayerMode 类中创建 dropDownMenu 类实例时,您将执行
dropDownMenu(
toggleCoinCallback: toogleCoin,
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7842 次 |
| 最近记录: |