Flutter – Barra de descarga

Flutter está repleto de bibliotecas para facilitar el desarrollo con menos código y más funcionalidades. Estamos de regreso con otro increíble paquete de Flutter hoy. 

Mostrar snackbar en las aplicaciones es una característica común de las aplicaciones actuales. Mostrar mensajes de error cuando algo sale mal o enviar notificaciones importantes a los usuarios de vez en cuando es importante para mantenerse conectado con los usuarios y mantenerlos actualizados sobre la información. Aunque había un paquete de snackbar simple disponible para mostrar snackbars en la aplicación que tenía funcionalidades muy limitadas, ahora tenemos una versión mejorada.  

La barra de descarga no se limita a la función de snackbar, sino que podemos personalizarla para que sea lo más útil y bonita posible. Para usar la barra de descarga , vamos a usar el increíble paquete another_flushbar que admite la seguridad nula en Flutter. En este artículo aprenderemos a crear diferentes tipos de snacks de forma fácil y rápida.

Implementación:

Paso 1: Agregar paquete.

Para usar el paquete, primero debemos instalarlo, para hacerlo, agregue la dependencia en el archivo pubspec.yaml .

Dart

dependencies:
  another_flushbar: ^1.10.28

Luego, ejecute pub get en la terminal para instalarlo. 

Paso 2: importa la biblioteca.

Importe la biblioteca al archivo en el que debe agregar la función snackbar como:

Dart

import 'package:flushbar/flushbar.dart';
import 'package:flushbar/flushbar_helper.dart';

Snackbar simple con Flushbar:

La barra de descarga simple es solo una barra de refrigerios con un mensaje de información y un título. Como puede ver en el siguiente código de simple flushbar , ¿qué tan simple es su código? Creamos una función simple show_Simple_Snackbar que muestra el widget Flushbar definido dentro. Aquí, estamos agregando mensajes y texto simples. Puede personalizar el texto y darle un tamaño, peso, estilo, etc. Flushbar también contiene titleText y la propiedad de texto del mensaje que son widgets, pero en el código a continuación, usamos el título de string y el mensaje de string, lo que le da una duración de 3 segundos para estar encendido. la pantalla.

Dart

void show_Simple_Snackbar(BuildContext context) {
    Flushbar(
      duration: Duration(seconds: 3),
      title: "This is simple flushbar",
      message: "Hey, you are a registered user now.",
    )..show(context);
  }

Producción:

Snackbar con Iconos:

A veces, mostrar solo texto no se ve bien. Quieres decir más. Se puede hacer a través de íconos, que agregan más significado al texto y mejoran la interfaz de usuario. A veces, también necesitamos mostrar diferentes tipos de información como advertencias, mensajes de error junto con sus respectivos íconos en la barra de bocadillos . Esto es muy fácil usando Flushbar, puede agregar cualquier ícono y personalizarlo según su elección con solo unas pocas líneas de código.

Dart

void show_Icon_Flushbar(BuildContext context) {
    Flushbar(
      icon: Icon(
        Icons.email_outlined,
        color: Colors.white,
        size: 30,
      ),
      backgroundColor: Color(0xFF0277BD),
      duration: Duration(seconds: 4),
      message: "This email is already registered.",
      messageSize: 18,
      titleText: Text("Flushbar with Icon.",
          style: TextStyle(
              fontSize: 16, fontWeight: FontWeight.bold, 
            color: Colors.white)),
    )..show(context);
  }

Producción:

Barra de descarga personalizada:

Bueno, mostrar snackbar ha pasado a un nivel diferente ahora. No es solo un simple snack bar , es cuestión de creatividad ahora. Puede personalizar el snackbar usando la biblioteca Flushbar que puede incluir un snackbar flotante , snackbar con diferentes colores, estilos, etc. No está limitado a usar la creatividad. Puede jugar con los parámetros de Flushbar como dar bordes redondeados, agregarle animación y mucho más. En el siguiente ejemplo, diseñé la barra de bocadillos con colores degradados y le di la sombra al cuadro. Se agregó animación para suavizarlo y le dio una dirección horizontal descartable.

Dart

void show_Custom_Flushbar(BuildContext context) {
    Flushbar(
      duration: Duration(seconds: 3),
      margin: EdgeInsets.all(8),
      padding: EdgeInsets.all(10),
  
      backgroundGradient: LinearGradient(
        colors: [
          Colors.pink.shade500,
          Colors.pink.shade300,
          Colors.pink.shade100
        ],
        stops: [0.4, 0.7, 1],
      ),
      boxShadows: [
        BoxShadow(
          color: Colors.black45,
          offset: Offset(3, 3),
          blurRadius: 3,
        ),
      ],
      dismissDirection: FlushbarDismissDirection.HORIZONTAL,
      forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
      title: 'This is a floating Flushbar',
      message: 'Welcome to Flutter community.',
      messageSize: 17,
    )..show(context);
  }

Producción:

Sin embargo, la creatividad de Flushbar no se detiene ahí. Puedes explorar sus más propiedades si quieres volverte más loco.

Uso de ayudantes Flushbar:

Anteriormente, mostrar un mensaje de error o de éxito era una tarea difícil y un proceso lento. Por esta razón, el widget Flushbar incluye ayudantes. Es una función simple que crea una barra de refrigerios genial para ahorrarle tiempo. Veamos cuánto más corto es crear la barra de refrigerios «Barra de descarga de información» con un ayudante.

Dart

void show_FlushbarHelper(BuildContext context) {
    FlushbarHelper.createInformation(
        title: "Flushbar Helper",
      message: "This is illegal action.")
      ..show(context);
  }

Producción:

Barra de descarga con botones:

A veces, después de mostrar un mensaje de error, desea redirigir al usuario a una página diferente según el error. Por lo tanto, podría haber cualquier botón para hacer clic con el error. ¿Qué pasa si puedes mostrar el botón con la barra de bocadillos ? ¿Es posible? Sí, puede hacerlo usando la propiedad mainButton de Flushbar. Al igual que en el código que se muestra a continuación, estoy envolviendo el texto «Haga clic en mí», dentro de un GestureDetector que es un elemento secundario del widget ButtonBar asignado a la propiedad mainButton de Flushbar. Cuando se muestra esta barra de bocadillos, el usuario puede hacer clic en el texto y hará lo que le dé dentro de onTap o onPressed , cualquiera que sea la propiedad.

Dart

void show_Button_Flushbar(BuildContext context) {
    Flushbar(
      mainButton: ButtonBar(
        children: [
          GestureDetector(
            onTap: () {
              print("You clicked me!");
            },
            child: Text(
              "Click me",
              style: TextStyle(color: Colors.white),
            ),
          )
        ],
      ),
      backgroundColor: Colors.black,
      title: "Flushbar with Button",
      message: "We require additional information.",
      messageSize: 17,
      duration: Duration(seconds: 4),
    )..show(context);
  }
}

Producción:

Aunque Flutter contiene su Snackbar predeterminado, se debe preferir el uso de Flushbar. Flushbar implica menos código repetitivo y contiene funciones ilimitadas para agregar. Puede diseñar cada parámetro del widget Flushbar y lo sorprenderá con su facilidad. Siempre que desee mostrar algo más que un mensaje de error o un mensaje de éxito, vaya a la biblioteca Flushbar.

Código completo del tutorial Flushbar:

Dart

import 'package:flutter/material.dart';
import 'package:another_flushbar/flushbar.dart';
import 'package:another_flushbar/flushbar_helper.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: 'Flutter Flushbar 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: Center(
        child: Column(
          children: [
            SizedBox(
              height: 40,
            ),
            ElevatedButton(
                onPressed: () {
                    
                  // invoking show_Simple_Snackbar function
                  show_Simple_Snackbar(context);
                },
                child: Text("Simple Snackbar with Flushbar")),
            ElevatedButton(
                onPressed: () {
                    
                  // calling function to show flushbar with icon
                  show_Icon_Flushbar(context);
                },
                child: Text("Flushbar with Icon")),
            ElevatedButton(
                onPressed: () {
                  //calling show Customized Flushbar
                  show_Custom_Flushbar(context);
                },
                child: Text("Flushbar with gradient colors")),
            ElevatedButton(
                onPressed: () {
                    
                  // calling function to FlushbarHelper
                  show_FlushbarHelper(context);
                },
                child: Text("Flushbar Helper")),
            ElevatedButton(
                onPressed: () {
                    
                  // calling function to show flushbar with button
                  show_Button_Flushbar(context);
                },
                child: Text("Flushbar with Button"))
          ],
        ),
      ),
    );
  }
  
  void show_Simple_Snackbar(BuildContext context) {
    Flushbar(
      duration: Duration(seconds: 3),
      title: "This is simple flushbar",
      message: "Hey, you are a registered user now.",
    )..show(context);
  }
  
  void show_Icon_Flushbar(BuildContext context) {
    Flushbar(
      icon: Icon(
        Icons.email_outlined,
        color: Colors.white,
        size: 30,
      ),
      backgroundColor: Color(0xFF0277BD),
      duration: Duration(seconds: 4),
      message: "This email is already registered.",
      messageSize: 18,
      titleText: Text("Flushbar with Icon.",
          style: TextStyle(
              fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.white)),
    )..show(context);
  }
  
  void show_Custom_Flushbar(BuildContext context) {
    Flushbar(
      duration: Duration(seconds: 3),
      margin: EdgeInsets.all(8),
      padding: EdgeInsets.all(10),
  
      backgroundGradient: LinearGradient(
        colors: [
          Colors.pink.shade500,
          Colors.pink.shade300,
          Colors.pink.shade100
        ],
        stops: [0.4, 0.7, 1],
      ),
      boxShadows: [
        BoxShadow(
          color: Colors.black45,
          offset: Offset(3, 3),
          blurRadius: 3,
        ),
      ],
        
      // All of the previous Flushbars could be dismissed
      // by swiping to any direction
      dismissDirection: FlushbarDismissDirection.HORIZONTAL,
        
      // The default curve is Curves.easeOut
      forwardAnimationCurve: Curves.fastLinearToSlowEaseIn,
      title: 'This is a floating Flushbar',
      message: 'Welcome to Flutter community.',
      messageSize: 17,
    )..show(context);
  }
  
  void show_FlushbarHelper(BuildContext context) {
    FlushbarHelper.createInformation(
        title: "Flushbar Helper", message: "This is illegal action.")
      ..show(context);
  }
  
  void show_Button_Flushbar(BuildContext context) {
    Flushbar(
      mainButton: ButtonBar(
        children: [
          GestureDetector(
            onTap: () {
              print("You clicked me!");
            },
            child: Text(
              "Click me",
              style: TextStyle(color: Colors.white),
            ),
          )
        ],
      ),
      backgroundColor: Colors.black,
      title: "Flushbar with Button",
      message: "We require additional information.",
      messageSize: 17,
      duration: Duration(seconds: 4),
    )..show(context);
  }
}

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 *