getButtonLocation function

Alignment getButtonLocation(
  1. GlobalKey<State<StatefulWidget>> buttonKey,
  2. BuildContext context
)

Implementation

Alignment getButtonLocation(GlobalKey buttonKey, BuildContext context) {
  final context = buttonKey.currentContext;

  if (context == null) {
    // Handle null context (button not yet rendered)
    print('Button context is null');
    return Alignment.center; // Return default center alignment
  }

  final renderBox = context.findRenderObject() as RenderBox?;
  if (renderBox == null) {
    // Handle null renderBox (could happen if the widget is still not rendered)
    print('RenderBox is null');
    return Alignment.center; // Return default center alignment
  }

  // Get position and size of the button
  final position = renderBox.localToGlobal(Offset.zero); // Position of the button
  final size = renderBox.size; // Size of the button

  // Get screen size
  final screenSize = MediaQuery.of(context).size;

  // Calculate the center position of the button relative to the screen
  final dx = (position.dx + size.width / 2) / screenSize.width;

  Alignment getButtonLocation(GlobalKey buttonKey, BuildContext context) {
    final context = buttonKey.currentContext;

    if (context == null) {
      // Handle null context (button not yet rendered)
      print('Button context is null');
      return Alignment.center; // Return default center alignment
    }

    final renderBox = context.findRenderObject() as RenderBox?;
    if (renderBox == null) {
      // Handle null renderBox (could happen if the widget is still not rendered)
      print('RenderBox is null');
      return Alignment.center; // Return default center alignment
    }

    // Get position and size of the button
    final position = renderBox.localToGlobal(Offset.zero); // Position of the button
    final size = renderBox.size; // Size of the button

    // Get screen size
    final screenSize = MediaQuery.of(context).size;

    // Calculate the center position of the button relative to the screen
    final dx = (position.dx + size.width / 2) / screenSize.width;
    final dy = (position.dy + size.height / 2) / screenSize.height;

    // Return the alignment for the transition (scaled to the range of -1 to 1)
    return Alignment(dx * 2 - 1, dy * 2 - 1);
  }

  final dy = (position.dy + size.height / 2) / screenSize.height;

  // Return the alignment for the transition (scaled to the range of -1 to 1)
  return Alignment(dx * 2 - 1, dy * 2 - 1);
}