Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Componente botón usando Flutter en lenguaje Dart

Tiempo de lectura: 2 minutos

En este post vamos crear un componente de botón personalizable en Flutter utilizando el widget ElevatedButton. Este componente nos permitirá crear botones con texto, icono y personalizar varios aspectos como el color, tamaño del texto y el ancho del botón.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'package:flutter/material.dart';
import '../util/constantes/Colores.dart';
class Boton extends StatelessWidget {
final Color? color; // Ahora es opcional y puede ser nulo
final Color? textColor;
final int? textSize;
final double? ancho;
final bool? fullWidth;
final String text;
final IconData? icon; // Ahora es opcional y puede ser nulo
final VoidCallback onPressed;
const Boton({
Key? key,
this.color, // Color no es requerido
this.textColor,
this.textSize,
this.ancho,
this.fullWidth,
required this.text,
this.icon, // Icono no es requerido
required this.onPressed,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: fullWidth != null && fullWidth == true
? double.infinity
: null, // Si fullWidth es verdadero, el ancho del botón es el máximo
height: ancho != null ? ancho : 50, // Ajusta el alto del botón
child: ElevatedButton(
onPressed: onPressed,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
icon != null
? Icon(
icon,
size: 24,
color: textColor != null ? textColor : ColorsApp.blanco,
) // Tamaño del icono
: Container(), // Si no hay icono, se muestra un contenedor vacío
icon != null ? SizedBox(width: 12) : SizedBox.shrink(),
Text(
text,
style: TextStyle(
fontSize: textSize != null
? textSize!.toDouble()
: 18, // Tamaño del texto
color: Colors.white,
fontWeight: FontWeight.bold, // Peso de la fuente
), // Ajusta el tamaño y el peso del texto
),
],
),
style: ElevatedButton.styleFrom(
primary: color != null ? color : ColorsApp.colorPersonalizado, // Color del botón
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10), // Bordes redondeados del botón
),
),
),
);
}
}
import 'package:flutter/material.dart'; import '../util/constantes/Colores.dart'; class Boton extends StatelessWidget { final Color? color; // Ahora es opcional y puede ser nulo final Color? textColor; final int? textSize; final double? ancho; final bool? fullWidth; final String text; final IconData? icon; // Ahora es opcional y puede ser nulo final VoidCallback onPressed; const Boton({ Key? key, this.color, // Color no es requerido this.textColor, this.textSize, this.ancho, this.fullWidth, required this.text, this.icon, // Icono no es requerido required this.onPressed, }) : super(key: key); @override Widget build(BuildContext context) { return Container( width: fullWidth != null && fullWidth == true ? double.infinity : null, // Si fullWidth es verdadero, el ancho del botón es el máximo height: ancho != null ? ancho : 50, // Ajusta el alto del botón child: ElevatedButton( onPressed: onPressed, child: Row( mainAxisSize: MainAxisSize.min, children: [ icon != null ? Icon( icon, size: 24, color: textColor != null ? textColor : ColorsApp.blanco, ) // Tamaño del icono : Container(), // Si no hay icono, se muestra un contenedor vacío icon != null ? SizedBox(width: 12) : SizedBox.shrink(), Text( text, style: TextStyle( fontSize: textSize != null ? textSize!.toDouble() : 18, // Tamaño del texto color: Colors.white, fontWeight: FontWeight.bold, // Peso de la fuente ), // Ajusta el tamaño y el peso del texto ), ], ), style: ElevatedButton.styleFrom( primary: color != null ? color : ColorsApp.colorPersonalizado, // Color del botón shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), // Bordes redondeados del botón ), ), ), ); } }
import 'package:flutter/material.dart';
import '../util/constantes/Colores.dart';

class Boton extends StatelessWidget {
  final Color? color; // Ahora es opcional y puede ser nulo
  final Color? textColor;
  final int? textSize;
  final double? ancho;
  final bool? fullWidth;
  final String text;
  final IconData? icon; // Ahora es opcional y puede ser nulo
  final VoidCallback onPressed;

  const Boton({
    Key? key,
    this.color, // Color no es requerido
    this.textColor,
    this.textSize,
    this.ancho,
    this.fullWidth,
    required this.text,
    this.icon, // Icono no es requerido
    required this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: fullWidth != null && fullWidth == true
          ? double.infinity
          : null, // Si fullWidth es verdadero, el ancho del botón es el máximo
      height: ancho != null ? ancho : 50, // Ajusta el alto del botón
      child: ElevatedButton(
        onPressed: onPressed,
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            icon != null
                ? Icon(
                    icon,
                    size: 24,
                    color: textColor != null ? textColor : ColorsApp.blanco,
                  ) // Tamaño del icono
                : Container(), // Si no hay icono, se muestra un contenedor vacío
            icon != null ? SizedBox(width: 12) : SizedBox.shrink(),
            Text(
              text,
              style: TextStyle(
                fontSize: textSize != null
                    ? textSize!.toDouble()
                    : 18, // Tamaño del texto
                color: Colors.white,
                fontWeight: FontWeight.bold, // Peso de la fuente
              ), // Ajusta el tamaño y el peso del texto
            ),
          ],
        ),
        style: ElevatedButton.styleFrom(
          primary: color != null ? color : ColorsApp.colorPersonalizado, // Color del botón
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(10), // Bordes redondeados del botón
          ),
        ),
      ),
    );
  }
}

Ahora que hemos creado el componente de botón personalizable, podemos utilizarlo fácilmente en cualquier parte de nuestra aplicación. Muestro a continuación un ejemplo de cómo usarlo:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'package:flutter/material.dart';
import 'ruta/a/boton.dart'; // Importar el componente de botón
class MiPagina extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Mi Aplicación'),
),
body: Center(
child: Boton(
text: 'Presionar',
onPressed: () {
// Acción al presionar el botón
print('Botón presionado');
},
),
),
);
}
}
import 'package:flutter/material.dart'; import 'ruta/a/boton.dart'; // Importar el componente de botón class MiPagina extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Mi Aplicación'), ), body: Center( child: Boton( text: 'Presionar', onPressed: () { // Acción al presionar el botón print('Botón presionado'); }, ), ), ); } }
import 'package:flutter/material.dart';
import 'ruta/a/boton.dart'; // Importar el componente de botón

class MiPagina extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Mi Aplicación'),
      ),
      body: Center(
        child: Boton(
          text: 'Presionar',
          onPressed: () {
            // Acción al presionar el botón
            print('Botón presionado');
          },
        ),
      ),
    );
  }
}

Espero que les sirva de ayuda. ¡Qué tengan un feliz día!

0

Deja un comentario