¿Cómo obtener widgets de coordenadas usando el paquete rect_getter en Flutter?

A veces necesitamos obtener la ubicación de un widget o mostrar algún widget superpuesto o algo similar sobre un widget cuya ubicación en la pantalla podría ser dinámica. En este artículo, vamos a discutir la forma de obtener las coordenadas de un widget usando el paquete rect_getter . Siga los pasos a continuación:

1. Crea una aplicación:

Cree una nueva aplicación flutter ejecutando el siguiente comando en su terminal:

flutter create your_app_name

Ahora abra su proyecto flutter en cualquier IDE como Android-Studio o VS-Code.

2. Cree una interfaz de usuario básica:

Ahora elimine todo el código repetitivo de lib/main.dart y agregue código para su interfaz de usuario. Para la demostración, he creado una interfaz de usuario básica con Columnas , Filas e Iconos.

Dart

import 'package:flutter/material.dart';
  
void main() {
  runApp(MaterialApp(home: MyApp()));
}
  
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
  
class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black26,
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Center(
          child: Text(
            'GeeksForGeeks',
            style: TextStyle(color: Colors.white,
                   fontWeight: FontWeight.bold),
          ),
        ),
      ),
      // Some basic UI with five Icons displayed in Rows and Columns
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Flexible(
                      flex: 1,
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      )),
                  Flexible(
                      flex: 1,
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ))
                ],
              ),
              Flexible(
                  flex: 1,
                  child: Icon(
                    Icons.message_outlined,
                    color: Colors.white,
                    size: 120,
                  )),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Flexible(
                      flex: 1,
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      )),
                  Flexible(
                      flex: 1,
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ))
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Producción: 

3. Ahora agregue el paquete rect_getter:

Para agregar el paquete rect_getter , ejecute el siguiente comando en su terminal:

flutter pub add rect_getter

4. Importando rect_getter:

Para usar rect_getter , impórtelo agregando la siguiente línea en su lib/main.dart :

Dart

import 'package:rect_getter/rect_getter.dart';

5. Obtener la ubicación de un widget usando rect_getter:

Para la ubicación de cada widget, queremos usar rect_getter, tenemos que declarar una clave global específica para cada widget. Dado que en este ejemplo estamos tratando de obtener la ubicación de cinco widgets, necesitamos declarar cinco claves globales. Así que agregue estas líneas justo al comienzo de la clase _MyAppState (en este caso, la suya podría diferir):

Dart

// Defining global keys for all the widgets we
// want to get coordinates of
var globalKey1 = RectGetter.createGlobalKey(),
globalKey2 = RectGetter.createGlobalKey(),
globalKey3 = RectGetter.createGlobalKey(),
globalKey4 = RectGetter.createGlobalKey(),
globalKey5 = RectGetter.createGlobalKey();

Ahora envuelva los cinco íconos (o el widget de destino en su caso) con un widget GestureDetector y ahora también envuelva este widget GestureDetector con un widget RectGetter . En el widget RectGetter, agregue un atributo clave y pase una clave global .

Ahora puede obtener acceso a las coordenadas del widget usando el siguiente código dentro del atributo onTap de GesturDetector y mostrar las coordenadas en un SnackBar :

Dart

// Add RectGetter as parent to the target widget
RectGetter(
  key: globalKey,
  child: GestureDetector(
          onTap: () {
                     // create a Rect instance
                     Rect rect = RectGetter.getRectFromKey(globalKey);
              
                     // Getting values of all four coordinate left, top, right and
                     // bottom using Rect instance 
                     var left = rect.left;
                     var top = rect.top;
                     var right = rect.right;
                     var bottom = rect.bottom;
                       
                     // Displaying the resultant coordinates in a SnackBar
                     ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                         content:
                           Text('LTRB :($left,$top,$right,$bottom)')));
                     },
                      child: YourWidget()
                    ),
                  )

Después de agregar todo este código a nuestro lib/main.dart , nuestro main.dart se verá así:

Dart

import 'package:flutter/material.dart';
import 'package:rect_getter/rect_getter.dart';
  
void main() {
  runApp(MaterialApp(home: MyApp()));
}
  
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
  
class _MyAppState extends State<MyApp> {
    
  // Defining global keys for all the widgets we
  // want to get coordinates of
  var globalKey1 = RectGetter.createGlobalKey(),
      globalKey2 = RectGetter.createGlobalKey(),
      globalKey3 = RectGetter.createGlobalKey(),
      globalKey4 = RectGetter.createGlobalKey(),
      globalKey5 = RectGetter.createGlobalKey();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black26,
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Center(
          child: Text(
            'GeeksForGeeks',
            style: TextStyle(color: Colors.white,
                             fontWeight: FontWeight.bold),
          ),
        ),
      ),
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Flexible(
                      
                      // Add RectGetter as parent to the target widget
                      child: RectGetter(
                    key: globalKey1,
                    child: GestureDetector(
                      onTap: () {
                          
                        // create a Rect instance
                        Rect rect = RectGetter.getRectFromKey(globalKey1);
                          
                        // Getting values of all four coordinate left, top, right and
                        // bottom using Rect instance 
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
                          
                        // Displaying the resultant coordinates in a SnackBar
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  )),
                  Flexible(
                      
                      // Add RectGetter as parent to the target widget
                      child: RectGetter(
                    key: globalKey2,
                    child: GestureDetector(
                      onTap: () {
                          
                        // create a Rect instance
                        Rect rect = RectGetter.getRectFromKey(globalKey2);
                          
                        // Getting values of all four coordinate left, top, right and
                        // bottom using Rect instance 
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
                          
                        // Displaying the resultant coordinates in a SnackBar
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  ))
                ],
              ),
              Flexible(
                  
                  // Add RectGetter as parent to the target widget
                  child: RectGetter(
                key: globalKey3,
                child: GestureDetector(
                  onTap: () {
                    //create a Rect instance
                    Rect rect = RectGetter.getRectFromKey(globalKey3);
                      
                    // Getting values of all four coordinate left, top, right and
                    // bottom using Rect instance 
                    var left = rect.left;
                    var top = rect.top;
                    var right = rect.right;
                    var bottom = rect.bottom;
                      
                    // Displaying the resultant coordinates in a SnackBar
                    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                        backgroundColor: Colors.green,
                        content: Text(
                          'LTRB :($left, $top, $right, $bottom)',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        )));
                  },
                  child: Icon(
                    Icons.message_outlined,
                    color: Colors.white,
                    size: 120,
                  ),
                ),
              )),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Flexible(
                      
                      // Add RectGetter as parent to the target widget
                      child: RectGetter(
                    key: globalKey4,
                    child: GestureDetector(
                      onTap: () {
                        //create a Rect instance
                        Rect rect = RectGetter.getRectFromKey(globalKey4);
                          
                        // Getting values of all four coordinate left, top, right and
                        // bottom using Rect instance 
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
  
                        // Displaying the resultant coordinates in a SnackBar
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  )),
                  Flexible(
                      
                      // Add RectGetter as parent to the target widget
                      child: RectGetter(
                    key: globalKey5,
                    child: GestureDetector(
                      onTap: () {
                          
                        // create a Rect instance
                        Rect rect = RectGetter.getRectFromKey(globalKey5);
                          
                        // Getting values of all four coordinate left, top, right and
                        // bottom using Rect instance 
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
                          
                        // Displaying the resultant coordinates in a SnackBar
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  ))
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Producción: 

Demostración de la aplicación1

5. Mostrar superposición de widgets usando las coordenadas

He usado las coordenadas de rect_getter para mostrar un punto de notificación sobre nuestro widget usando Overlay. Verifique el código a continuación:

Dart

import 'package:flutter/material.dart';
import 'package:rect_getter/rect_getter.dart';
  
void main() {
  runApp(MaterialApp(home: MyApp()));
}
  
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
  
class _MyAppState extends State<MyApp> {
  var globalKey1 = RectGetter.createGlobalKey(),
      globalKey2 = RectGetter.createGlobalKey(),
      globalKey3 = RectGetter.createGlobalKey(),
      globalKey4 = RectGetter.createGlobalKey(),
      globalKey5 = RectGetter.createGlobalKey();
  
  showOverlayDot(BuildContext context,
                 double left, double top) async {
    OverlayState overlayState = Overlay.of(context);
    OverlayEntry overlayEntry;
    overlayEntry = OverlayEntry(builder: (context) {
      return Positioned(
          left: left,
          top: top,
          child: Icon(
            Icons.circle,
            color: Colors.red,
          ));
    });
  
    overlayState.insert(overlayEntry);
    await Future.delayed(Duration(seconds: 2));
    overlayEntry.remove();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black26,
      appBar: AppBar(
        backgroundColor: Colors.green,
        title: Center(
          child: Text(
            'GeeksForGeeks',
            style: TextStyle(color: Colors.white,
                             fontWeight: FontWeight.bold),
          ),
        ),
      ),
      body: SafeArea(
        child: Container(
          padding: EdgeInsets.all(16),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Flexible(
                      child: RectGetter(
                    key: globalKey1,
                    child: GestureDetector(
                      onTap: () {
                        Rect rect = RectGetter.getRectFromKey(globalKey1);
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
  
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                        showOverlayDot(this.context, left, top);
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  )),
                  Flexible(
                      child: RectGetter(
                    key: globalKey2,
                    child: GestureDetector(
                      onTap: () {
                        Rect rect = RectGetter.getRectFromKey(globalKey2);
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
  
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                        showOverlayDot(this.context, left, top);
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  ))
                ],
              ),
              Flexible(
                  child: RectGetter(
                key: globalKey3,
                child: GestureDetector(
                  onTap: () {
                    Rect rect = RectGetter.getRectFromKey(globalKey3);
                    var left = rect.left;
                    var top = rect.top;
                    var right = rect.right;
                    var bottom = rect.bottom;
  
                    ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                        backgroundColor: Colors.green,
                        content: Text(
                          'LTRB :($left, $top, $right, $bottom)',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        )));
                    showOverlayDot(this.context, left, top);
                  },
                  child: Icon(
                    Icons.message_outlined,
                    color: Colors.white,
                    size: 120,
                  ),
                ),
              )),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                mainAxisSize: MainAxisSize.max,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Flexible(
                      child: RectGetter(
                    key: globalKey4,
                    child: GestureDetector(
                      onTap: () {
                        Rect rect = RectGetter.getRectFromKey(globalKey4);
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
  
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                        showOverlayDot(this.context, left, top);
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  )),
                  Flexible(
                      child: RectGetter(
                    key: globalKey5,
                    child: GestureDetector(
                      onTap: () {
                        Rect rect = RectGetter.getRectFromKey(globalKey5);
                        var left = rect.left;
                        var top = rect.top;
                        var right = rect.right;
                        var bottom = rect.bottom;
  
                        ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                            backgroundColor: Colors.green,
                            content: Text(
                              'LTRB :($left, $top, $right, $bottom)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            )));
                        showOverlayDot(this.context, left, top);
                      },
                      child: Icon(
                        Icons.message_outlined,
                        color: Colors.white,
                        size: 70,
                      ),
                    ),
                  ))
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Producción: 

Demostración de la aplicación 2

Publicación traducida automáticamente

Artículo escrito por curiousyuvi y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *