如何获取 GridView 颤振内小组件的偏移量



我正在尝试在 GridView 中向 Inkwell 小部件添加爆炸效果,但我需要找到它的偏移量,到目前为止我已经尝试过:

GridView.builder(
itemCount: 10,
itemBuilder: (ctx, ind) {
return InkWell(
onTap: () async {
try {
final RenderBox box = ctx.findRenderObject();
Offset position = box.localToGlobal(Offset.zero,
ancestor: context.findRenderObject()
);
double x = position.dx;
double y = position.dy;
double w = box.size.width;
Future.delayed(Duration(milliseconds: 100)).then(
(_) => _particleField.lineExplosion(x, y, w)
);
} catch (e) {
print(e);
}
},
child: Center(
child: Text("${ind + 1},000,000")
),  
);
},
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, 
childAspectRatio: 3
),
)

但我收到此错误:

类型"RenderSliverGrid"不是类型"RenderBox"的子类型

这是你要找的吗?

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
body: GridExample(),
),
);
}
}
class GridExample extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GridView.builder(
itemCount: 10,
itemBuilder: (ctx, ind) {
return _Item('${ind + 1},000,000');
},
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, childAspectRatio: 3),
);
}
}
class _Item extends StatelessWidget {
_Item(this.title);
String title;
final GlobalKey _globalKey = GlobalKey();
@override
Widget build(BuildContext context) {
return InkWell(
key: _globalKey,
onTap: () async {
final RenderBox referenceBox =
_globalKey.currentContext.findRenderObject();
final position = referenceBox.localToGlobal(Offset.zero);
final x = position.dx;
final y = position.dy;
final w = referenceBox.size.width;
Future.delayed(Duration(milliseconds: 100))
.then((_) => _particleFieldLineExplosion(x, y, w));
},
child: Center(child: Text(title)),
);
}
_particleFieldLineExplosion(x, y, w) {
print(x);
print(y);
print(w);
}
}

添加一个GlobalKey作为InkWell的键

itemBuilder: (ctx, ind) {
GlobalKey _key=GlobalKey();
return InkWell(
key:_key;
);
}

然后你可以简单地更换

final RenderBox box = _key.currentContext.findRenderObject();

相关内容

  • 没有找到相关文章

最新更新