gpt4 book ai didi

flutter - 获取容器在 Flutter 上的 "y"位置

转载 作者:IT王子 更新时间:2023-10-29 07:23:31 25 4
gpt4 key购买 nike

我想获得容器、小部件、堆栈等的“y”位置。当它显示在屏幕中央时,我想从图像(视频预览图像)更改为视频文件。我该怎么办?

我找到了屏幕高度。我计算了屏幕中心。我找不到容器位置。

我创建了这样一个示例,但该项目没有位于中心。可能我在这里犯了算法错误?

class _DedectCenterState extends State<DedectCenter> {

Size _wSize;
int listSize = 4;
List<GlobalKey> _key = [];

ScrollController _sController;

_scrollListener() {
print("scrolling : " + _sController.offset.toString());

setState(() {
getPosition();
});}

@override
void initState() {

for(int i=0; i < listSize; i++) {
_key[i] = new GlobalKey();
}

_sController = ScrollController();

_sController.addListener(_scrollListener);
super.initState();
}

void getPosition(){

double _wCenterTop = (_wSize.height / 2) - 150.0;
double _wCenterBottom = (_wSize.height / 2) + 150.0;

print("center bottom: " + _wCenterBottom.toString());
print("center top: " + _wCenterTop.toString());


for(int i=0; i < listSize; i++) {

//add key to your widget, which position you need to find
RenderBox box = _key[i].currentContext.findRenderObject();
Offset position = box.localToGlobal(Offset.zero); //this is global position
double y = position.dy; //this is y - I think it's what you want

print("key $i y position: " + y.toString());

if(y < _wCenterTop && y > _wCenterBottom) print("key $i center: " + y.toString());
}}


Widget build(BuildContext context) {
_wSize = MediaQuery.of(context).size;

return new Scaffold(
appBar: null,
body: new ListView(
controller: _sController,
children: <Widget>[
Row(
children: <Widget>[
Column(
children: <Widget>[
Container(
key: _key[0],
margin: EdgeInsets.only(top:100.0),
height: 140.0,
width: _wSize.width,
child: new Image.asset('assets/images/physical/a1.png'),
)],)],
),
Row(
children: <Widget>[
Column(
children: <Widget>[
Container(
key: _key[1],
margin: EdgeInsets.only(top:100.0),
height: 140.0,
width: _wSize.width,
child: new Image.asset('assets/images/physical/a2.png'),
),],)],
),
Row(
children: <Widget>[
Column(
children: <Widget>[
Container(
margin: EdgeInsets.only(top:100.0),
key: _key[2],
height: 140.0,
width: _wSize.width,
child: new Image.asset('assets/images/physical/a3.png'),
),],)],),
Row(
children: <Widget>[
Column(
children: <Widget>[
Container(
margin: EdgeInsets.only(top:100.0),
key: _key[3],
width: _wSize.width,
height: 140.0,
child: new Image.asset('assets/images/physical/a4.png'),
),
],
)
],),]));}}

最佳答案

您可以使用 GlobalKey 获取小部件的大小或位置

GlobalKey key = GlobalKey(); // declare a global key

将键添加到您的小部件,您需要找到它的位置

Container(
key: key,
...
);

使用渲染框获取位置

RenderBox box = key.currentContext.findRenderObject() as RenderBox;
Offset position = box.localToGlobal(Offset.zero); //this is global position
double y = position.dy; //this is y - I think it's what you want

关于flutter - 获取容器在 Flutter 上的 "y"位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54291245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com