本文主要是介绍Flutter GlobalKey用处,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
拖动示例class DragWidget extends StatefulWidget{@override_DragWidgetState createState() {// TODO: implement createStatereturn _DragWidgetState();}
}class _DragWidgetState extends State<DragWidget> {GlobalKey stackKey = GlobalKey();GlobalKey btnKey = GlobalKey();double _left = 0.0;double _top = 0.0;double _areaWidth = 0.0;double _areaHeight = 0.0;@overridevoid initState() {// TODO: implement initStatesuper.initState();WidgetsBinding.instance.addPostFrameCallback((duration) {setState(() {_areaWidth = stackKey.currentContext.size.width - btnKey.currentContext.size.width;_areaHeight = stackKey.currentContext.size.height - btnKey.currentContext.size.height;});});}@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Stack(key: stackKey,children: <Widget>[Positioned(top: _top,left: _left,child: GestureDetector(child: FloatingActionButton(key: btnKey,child: Text('drag'),),onPanUpdate: (e) {setState(() {_left += e.delta.dx;_top += e.delta.dy;if (_left < 0) {_left = 0;} else if (_left > _areaWidth) {_left = _areaWidth;}if (_top < 0) {_top = 0;} else if (_top > _areaHeight) {_top = _areaHeight;}});},))],);}
}效果展示将onPanUpdate改为onVerticalDragUpdate即可变为只能在竖直方向上拖动,onHorizontalDragUpdate同理。三、缩放
class ScaleWidget extends StatefulWidget{@override_ScaleWidgetState createState() {// TODO: implement createStatereturn _ScaleWidgetState();}
}
class _ScaleWidgetState extends State<ScaleWidget>{double _width = 300.0;double _height = 200.0;@overrideWidget build(BuildContext context) {// TODO: implement buildreturn Center(child: GestureDetector(child: Container(constraints: BoxConstraints.tight(Size(_width, _height)),color: Colors.blue,),onScaleUpdate: (e) {print(e);setState(() {// 限制宽度缩放比例在0.7-1.2之间,如果超过这个范围,Container会变为原来的大小_width = 300* e.scale.clamp(0.7, 1.2);_height = 200*e.scale.clamp(0.7, 1.2);});},));}
}
Flutter GlobalKey的使用
这篇关于Flutter GlobalKey用处的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!