0

这是我的颤动代码,我想在单击我调用 closeOverlay() 的图标按钮时关闭覆盖,但它显示错误为:

Try moving the declaration to before the first use, or renaming the local variable so that it doesn't hide a name from an enclosing scope.

我还尝试将 overlayEntry.remove 函数直接调用到 onPressed 函数,因为它给出了一个类似的错误,即在声明它之前无法引用 overlayEntry 虽然它是在此处调用它之前声明的。

showTeacherDetails(BuildContext context) {
    OverlayState overlayState = Overlay.of(context);
    OverlayEntry overlayEntry = OverlayEntry(
        builder: (context) => Positioned(
            width: SizeConfig.blockSizeHorizontal * 25,
            height: SizeConfig.blockSizeVertical * 92,
            top: SizeConfig.blockSizeVertical * 8,
            left: SizeConfig.blockSizeHorizontal * 75,
            
            child: Container(
                padding: EdgeInsets.symmetric(
                    vertical: SizeConfig.blockSizeVertical * 0.5,
                    horizontal: SizeConfig.blockSizeHorizontal * 1),
                color: Colors.white,
                child: Column(
                  children: [
                    IconButton(
                      icon: Icon(Icons.close, size: 40,),
                      onPressed: closeOverlay() //error
                    ),
                  ],
                ))));
    overlayState.insert(overlayEntry);
    closeOverlay(){
      overlayEntry.remove();
    }
    
  }
}
4

1 回答 1

0

只需声明变量,然后分配它

showTeacherDetails(BuildContext context) {
OverlayEntry overlayEntry; //We declare

overlayEntry = OverlayEntry( //We assign
    builder: (context) => Positioned(
        width: SizeConfig.blockSizeHorizontal * 25,
        height: SizeConfig.blockSizeVertical * 92,
        top: SizeConfig.blockSizeVertical * 8,
        left: SizeConfig.blockSizeHorizontal * 75,
        
        child: Container(
            padding: EdgeInsets.symmetric(
                vertical: SizeConfig.blockSizeVertical * 0.5,
                horizontal: SizeConfig.blockSizeHorizontal * 1),
            color: Colors.white,
            child: Column(
              children: [
                IconButton(
                  icon: Icon(Icons.close, size: 40,),
                  onPressed: (){
                      // add null checks to the overlay before removing
                      overlayEntry?.remove()
                     }
                ),
              ],
            ))));
}
于 2020-10-09T20:44:04.327 回答