Flutter 实现一个容器内部元素可平移、缩放和旋转等功能(十一)
Flutter: 3.35.7
前面我们实现了网格辅助线等功能,拥有这些功能,我们就能很好的定位元素在容器内的位置。今天我们就主要实现元素层级的相关操作。
在我们之前的功能中,元素个数比较少,当元素个数达到一定数量后,肯定会存在覆盖的情况,我们无法保证需要操作的元素一定是在顶层,所以就需要对层级进行辅助控制。而且层级操作主要是针对当前选中的元素,所以在未选中元素的时候就不允许点击。
元素层级的控制主要分为如下几类:
- 操作当前选中元素的层级
- 选中点击坐标内的某个层级的元素,不至于一定要保证它在顶层也可选中进行操作
因为元素层级的操作涉及到几个,以开启按钮位置为基准定位展示,所以要使用到OverlayEntry,我们单独抽取结构:
import'package:flutter/material.dart';import'base_icon_button.dart';classLevelBarextendsStatefulWidget{constLevelBar({super.key,requiredthis.onChangeUsePosition,requiredthis.usePosition,requiredthis.disabled,});finalFunction()onChangeUsePosition;finalbool usePosition;finalbool disabled;@overrideState<LevelBar>createState()=>_LevelBarState();}class_LevelBarStateextendsState<LevelBar>{/// 用于获取定位信息finalGlobalKey_globalKey=GlobalKey();/// 容器OverlayEntry?_overlayEntry;/// 宽高定位信息用于定位容器double _barWidth=0;double _barHeight=0;double _barTop=0;double _barLeft=0;@overridevoiddidUpdateWidget(covariantLevelBaroldWidget){super.didUpdateWidget(oldWidget);// 当使用层级工具,展示,不使用,隐藏if(oldWidget.usePosition!=widget.usePosition){if(widget.usePosition==false){_hideLevelBar();}else{WidgetsBinding.instance.addPostFrameCallback((_){_showLevelBar();});}}}@overridevoiddispose(){_globalKey.currentState?.dispose();_hideLevelBar();super.dispose();}/// 隐藏层级工具栏void_hideLevelBar(){if(_overlayEntry!=null){_overlayEntry?.remove();_overlayEntry=null;}}/// 展示层级工具栏void_showLevelBar(){_getDimensions();_hideLevelBar();// 创建 OverlayEntry_overlayEntry=OverlayEntry(builder:(context)=>Positioned(top:_barHeight+_barTop,left:_barLeft-100+_barWidth/2,child:Material(borderRadius:BorderRadius.circular(10),child:Container(width:200,decoration:BoxDecoration(color:Color(0xFFF0F0F0),border:Border.all(color:Colors.blueAccent,width:2,),borderRadius:BorderRadius.circular(10),),child:Row(mainAxisAlignment:MainAxisAlignment.center,children:[BaseIconButton(iconSrc:'assets/images/icon_top.png',onPressed:(){},),BaseIconButton(iconSrc