变量声明如何影响onTap事件?

问题描述 投票:1回答:1

因此,我试图使用InkWell类为我的游戏应用检测手势,并且我尝试了多种方法来使手势事件发生。

[我发现适用于我的游戏应用程序的手势事件后,我注意到,如果尝试切换名为mycolor的变量,该变量用于切换Rectagular的颜色,如下所示,将在Widget Build()外部声明。有效 !

但是当我切换回Widget Build()内部进行声明时。没有!

为什么变量声明会影响我的手势事件的结果?

Before declare variable outside WidgetBuild()

After declare variable outside WidgetBuild()

class GameStructureState extends State<GameStructure>{

bool mycolor = true;
@override
 Widget build(BuildContext context) {
 double w = MediaQuery.of(context).size.width;
 double h = MediaQuery.of(context).size.height;
 //bool mycolor = true;
 //debugPaintPointersEnabled = true;
 return Center(
   child: Column(
     children: <Widget>[
      Row( children: <Widget>[
        InkWell(
          onTap: (){
            setState(() {
              mycolor = false;
              print(mycolor);
            });
          },
          child: Padding(
            padding: EdgeInsets.all(w/30),
            child: Container(width: 100.0,height: 100.0,color: mycolor ? Colors.blue:Colors.green,child: Text(mycolor.toString()),),
          ),
        ),
      ],
      ),
    ],
  ),
);
}
}
android flutter
1个回答
0
投票

当小部件中的布尔值被拒绝时:

当您的应用首次运行时,myColor将设置为true。

当您在手势检测器中声明setState()并将myColor设置为false时,它将导致整个widgetBuild函数再次重新运行。因此,myColor将重新初始化并再次设置为true。

因此,即使您声明布尔值myColor等于false,当小部件重建时,它也会重新设置为true。

当BOOL被拒绝在小部件上时:

当您的应用首次运行时,myColor被声明为true。

当您在手势检测器中声明setState()并将myColor设置为false时,它将导致整个widgetBuild函数再次重新运行。但是这一次,由于myColor在小部件构建外部声明,因此不会重新初始化。因此,它并没有设置为true。相反,它仍然为假。这就是您的代码起作用的原因。

© www.soinside.com 2019 - 2024. All rights reserved.