如何在Flutter的GridView中获取一个小部件的位置偏移量

6

我正在尝试为GridView中的Inkwell Widget添加一个爆炸效果,但我需要找到它的偏移量。目前我已经尝试了以下方法:

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'的子类型


尝试使用RenderSliver而不是RenderBox - Xihuny
@Xihuny 我该如何在RenderSliver上使用localToGlobal()方法? - geekymano
2个回答

10

这是你所寻找的吗?

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);
  }
}

2

GlobalKey作为InkWell的键添加

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

然后您可以简单地替换


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接