LoginSignup
8
3

More than 5 years have passed since last update.

FlutterでWidgetのグローバル座標を取得する

Posted at

FlutterでレイアウトしたWidgetの表示されている座標を取得したかったので調べました。RenderBoxを使うとできました。RenderBoxにアクセスするためにはWidgetにKeyを渡す必要があります。なるほど、Keyってこういう時に使うんですね。

class MyWidget extends StatelessWidget {
  final widgetKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My app'),
      ),
      body: Stack(
        children: <Widget>[
          Positioned(
            right: 100,
            bottom: 200,
            child: FlutterLogo(
              key: widgetKey, // 座標を取得したいWidgetにkeyを付けると、後から参照できる
              size: 64,
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // widgetKeyを付けたWidgetのグローバル座標を取得する
          final RenderBox box = widgetKey.currentContext.findRenderObject();
          final globalOffset = box.localToGlobal(Offset.zero);
          print(globalOffset);
        },
        child: Icon(Icons.add),
      ),
    );
  }
}
8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3