Flutter – Alertas RFlutter

En Flutter, rflutter_alert es útil para crear alertas en aplicaciones fácilmente. Es una forma personalizable y mejor de crear alertas en Flutter. En este artículo, veremos los diferentes estilos de alertas que podemos crear con esta increíble biblioteca de Flutter. Sigue el artículo para conocerlo.

Agregando la dependencia:

Para instalar rflutter_alert , agréguelo en la sección de dependencia del archivo pubspec.yaml . Luego configúralo usando pub get.

Importar la dependencia:

Para usar este paquete, impórtelo en el archivo main.dart o en cualquier archivo en el que queramos usar la función de alerta.

Dart

import 'package:rflutter_alert/rflutter_alert.dart';

Implementación:

Para crear un cuadro de diálogo de alerta, necesitamos usar el widget Alert(). Requiere un argumento de contexto y el método show() se usa para mostrar la alerta en la pantalla. Las características que ofrece este widget son:

  • Contexto (Requerido)
  • ¿Cuerda? identificación
  • ¿Tipo de alerta? escribe
  • Estilo AlertStyle = const AlertStyle()
  • ¿Inserciones de borde? relleno
  • widget? imagen
  • ¿Cuerda? título
  • ¿Cuerda? descripción
  • Contenido del widget = const SizedBox()
  • ¿Lista<botón de diálogo>? botones
  • ¿Función? cerrarFunción
  • widget? cerrarIcono
  • bool onWillPopActive = falso
  • ¿Función de widget (Contexto de compilación, Animación <doble>, Animación <doble>, Widget)? alertaAnimación
  • bool useRootNavigator = verdadero,

Alerta sencilla:

Dart

ElevatedButton(
       child: Text("Click Me"),
       onPressed: () {
          Alert(
               context: context,
               title: "RFlutter Alert",
               desc: "GeeksForGeeks is awesome.").show();
            },
 ),

Producción:

Alerta con Botones:

Dart

Alert(
                context: context,
                type: AlertType.info,
                title: "GeeksForGeeks",
                desc: "Create more awesome alerts with RFlutter Alert.",
                buttons: [
                  DialogButton(
                    child: Text(
                      "Done",
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                    onPressed: () => Navigator.pop(context),
                    width: 120,
                  ),
                  DialogButton(
                    child: Text(
                      "Cancel",
                      style: TextStyle(color: Colors.white, fontSize: 20),
                    ),
                    onPressed: () => Navigator.pop(context),
                    width: 120,
                  )
                ],
              ).show();

Producción:

Alerta con imagen:

Dart

Alert(
       context: context,
       title: "GeeksForGeeks",
       desc: "Create Awesome alerts with RFlutter Alert.",
       image: Image.network("https://i.stack.imgur.com/xLOYo.png"),
 ).show();

Producción:

Alerta personalizada:

Dart

Alert(
                  context: context,
                  title: "Sign Up",
                  content: Column(
                    children: <Widget>[
                      TextField(
                        decoration: InputDecoration(
                          icon: Icon(Icons.email),
                          labelText: 'Email',
                        ),
                      ),
                      TextField(
                        obscureText: true,
                        decoration: InputDecoration(
                          icon: Icon(Icons.lock),
                          labelText: 'Password',
                        ),
                      ),
                    ],
                  ),
                  buttons: [
                    DialogButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text(
                        "SIGN UP",
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    )
                  ]).show();

Producción:

Alerta con Animación:

También podemos agregar animación al widget Alert() usando la propiedad animationType . Si queremos que la alerta aparezca desde arriba, podemos usar AnimationType.fromTop y si desde abajo usamos AnimationType.fromBottom. También podemos darle animationDuration y estilo personalizado usando AlertStyle().

Dart

Alert(
                       title: "GeeksForGeeks",
                       context: context,
                       style: AlertStyle(
                         alertAlignment: Alignment.center,
                         animationType: AnimationType.fromBottom,
                         isCloseButton: false,
                         isOverlayTapDismiss: false,
                         descStyle: TextStyle(fontWeight: FontWeight.bold),
                         descTextAlign: TextAlign.start,
                         animationDuration: Duration(milliseconds: 300),
                         alertBorder: RoundedRectangleBorder(
                           borderRadius: BorderRadius.circular(0.0),
                           side: BorderSide(
                             color: Colors.red,
                           ),
                         ),
                         titleStyle: TextStyle(
                           color: Colors.green,
                         ),
                       )).show();

Código fuente completo:

Dart

import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
  
void main() {
  runApp(const MyApp());
}
  
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'RFlutter Alert Tutorial',
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("GeeksForGeeks"),
        centerTitle: true,
      ),
      body: Container(
        child: Center(
          child: Column(
            children: [
              SizedBox(height: 100),
              ElevatedButton(
                child: Text("Click One"),
                onPressed: () {
                  Alert(
                          context: context,
                          title: "RFlutter Alert",
                          desc: "GeeksForGeeks is awesome.")
                      .show();
                },
              ),
              ElevatedButton(
                  onPressed: () {
                    Alert(
                      context: context,
                      type: AlertType.info,
                      title: "GeeksForGeeks",
                      desc: "Create more awesome alerts with RFlutter Alert.",
                      buttons: [
                        DialogButton(
                          child: Text(
                            "Done",
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                          onPressed: () => Navigator.pop(context),
                          width: 120,
                        ),
                        DialogButton(
                          child: Text(
                            "Cancel",
                            style: TextStyle(color: Colors.white, fontSize: 20),
                          ),
                          onPressed: () => Navigator.pop(context),
                          width: 120,
                        )
                      ],
                    ).show();
                  },
                  child: Text("Click Two")),
              ElevatedButton(
                  onPressed: () {
                    Alert(
                      context: context,
                      title: "GeeksForGeeks",
                      desc: "Create Awesome alerts with RFlutter Alert.",
                      image:
                          Image.network("https://i.stack.imgur.com/xLOYo.png"),
                    ).show();
                  },
                  child: Text("Click Three")),
              ElevatedButton(
                  onPressed: () {
                    Alert(
                        context: context,
                        title: "Sign Up",
                        content: Column(
                          children: <Widget>[
                            TextField(
                              decoration: InputDecoration(
                                icon: Icon(Icons.email),
                                labelText: 'Email',
                              ),
                            ),
                            TextField(
                              obscureText: true,
                              decoration: InputDecoration(
                                icon: Icon(Icons.lock),
                                labelText: 'Password',
                              ),
                            ),
                          ],
                        ),
                        buttons: [
                          DialogButton(
                            onPressed: () => Navigator.pop(context),
                            child: Text(
                              "SIGN UP",
                              style:
                                  TextStyle(color: Colors.white, fontSize: 20),
                            ),
                          )
                        ]).show();
                  },
                  child: Text("Click Four")),
              ElevatedButton(
                  onPressed: () {
                    Alert(
                        title: "GeeksForGeeks",
                        context: context,
                        style: AlertStyle(
                          alertAlignment: Alignment.center,
                          animationType: AnimationType.fromBottom,
                          isCloseButton: false,
                          isOverlayTapDismiss: false,
                          descStyle: TextStyle(fontWeight: FontWeight.bold),
                          descTextAlign: TextAlign.start,
                          animationDuration: Duration(milliseconds: 300),
                          alertBorder: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(0.0),
                            side: BorderSide(
                              color: Colors.red,
                            ),
                          ),
                          titleStyle: TextStyle(
                            color: Colors.green,
                          ),
                        )).show();
                  },
                  child: Text("Click Five"))
            ],
          ),
        ),
      ),
    );
  }
}

Producción:

Publicación traducida automáticamente

Artículo escrito por rn540 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 *