Bongani  Ngema

Bongani Ngema

1669991520

Add Edit Delete Button in Yajra DataTables in Laravel

In Laravel using Yajra DataTables package, you can easily add pagination in less time.

To add edit delete button in the DataTable need to use addColumn() method.

In this tutorial, I am assuming you have already installed the Yajra package, if not then you can view this tutorial.

I am implementing this on Laravel 9.

Contents

  1. Add Database configuration
  2. Create a Table
  3. Create Model
  4. Create Controller
  5. Create Route
  6. Create View
  7. Output
  8. Conclusion

1. Add Database configuration

Open .env file to update the database connection.

Specify the host, database name, username, and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tutorial
DB_USERNAME=root
DB_PASSWORD=

2. Create a Table

  • Create a new table employees using migration.

php artisan make:migration create_employees_table

  • Now, navigate to database/migrations/ folder from the project root.
  • Find a PHP file that ends with create_employees_table and open it.
  • Define the table structure in the up() method.
public function up()
{
    Schema::create('employees', function (Blueprint $table) {
       $table->id();
       $table->string('emp_name',60);
       $table->string('email',80);
       $table->string('gender',20);
       $table->string('city',100);
       $table->smallInteger('status',2);
       $table->timestamps();
    });
}
  • Run the migration –

php artisan migrate

  • The table is been created and I added some records to it.

3. Create Model

  • Create Employees Model –

php artisan make:model Employees

  • Open app/Models/Employees.php file.
  • Specify mass assignable Model attributes – emp_name, email, gender, city, and status using the $fillable property.

Completed Code

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employees extends Model
{
    use HasFactory;
    protected $fillable = [ 
        'emp_name','email','gender','city','status'
    ];
}

4. Create Controller

  • Create PagesController controller.

php artisan make:controller PagesController

  • Import Employees model and DataTables.
  • Create 5 methods –
    • index() – Load index view.
    • getDataTableData() – Using this method load DataTable data.

Pass $employees in Datatables::of() to generate return response.

Using addColumn() add edit and delete buttons. In the edit button store employee id in data-id attribute and to open Bootstrap modal add data-bs-toggle and data-bs-target attribute.

In the delete button also store employee id in data-id attribute.

  • getEmployeeData() – Using this method fetch a record by POST id from employees table. Initialize $response Array with fetched data and return in JSON format.
  • updateEmployee() – Using this method update a employee record.
  • deleteEmployee() – Using this method delete a employee record by POST id.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Employees;
use DataTables;

class PagesController extends Controller
{

     public function index(){
         return view('index');
     }

     // DataTable data
     public function getDataTableData(){
         $employees = Employees::select('*');

         return Datatables::of($employees)
            ->addIndexColumn()
            ->addColumn('status', function($row){

                 if($row->status == 1){
                      return "Active";
                 }else{
                      return "Inactive";
                 }

            }) 
            ->addColumn('action', function($row){

                 // Update Button
                 $updateButton = "<button class='btn btn-sm btn-info updateUser' data-id='".$row->id."' data-bs-toggle='modal' data-bs-target='#updateModal' ><i class='fa-solid fa-pen-to-square'></i></button>";

                 // Delete Button
                 $deleteButton = "<button class='btn btn-sm btn-danger deleteUser' data-id='".$row->id."'><i class='fa-solid fa-trash'></i></button>";

                 return $updateButton." ".$deleteButton;

            }) 
            ->make();
     }

     // Read Employee record by ID
     public function getEmployeeData(Request $request){

         ## Read POST data 
         $id = $request->post('id');

         $empdata = Employees::find($id);

         $response = array();
         if(!empty($empdata)){

             $response['emp_name'] = $empdata->emp_name;
             $response['email'] = $empdata->email;
             $response['city'] = $empdata->city;
             $response['gender'] = $empdata->gender;

             $response['success'] = 1;
         }else{
             $response['success'] = 0;
         }

         return response()->json($response);

     }

     // Update Employee record
     public function updateEmployee(Request $request){
         ## Read POST data
         $id = $request->post('id');

         $empdata = Employees::find($id);

         $response = array();
         if(!empty($empdata)){
              $updata['emp_name'] = $request->post('emp_name');
              $updata['email'] = $request->post('email');
              $updata['gender'] = $request->post('gender');
              $updata['city'] = $request->post('city');

              if($empdata->update($updata)){
                   $response['success'] = 1;
                   $response['msg'] = 'Update successfully'; 
              }else{
                   $response['success'] = 0;
                   $response['msg'] = 'Record not updated';
              }

         }else{
              $response['success'] = 0;
              $response['msg'] = 'Invalid ID.';
         }

         return response()->json($response); 
     }

     // Delete Employee
     public function deleteEmployee(Request $request){

         ## Read POST data
         $id = $request->post('id');

         $empdata = Employees::find($id);

         if($empdata->delete()){
             $response['success'] = 1;
             $response['msg'] = 'Delete successfully'; 
         }else{
             $response['success'] = 0;
             $response['msg'] = 'Invalid ID.';
         }

         return response()->json($response); 
     }

}

5. Create Route

  • Open routes/web.php file.
  • Create 5 routes –
    • / – Load index view.
    • /getdatatabledata – GET type route to fetch DataTable data.
    • /getEmployeeData – POST type route to fetch a record for displaying in Bootstrap modal for update.
    • /updateEmployee – POST type route to update a record.
    • /deleteEmployee – POST type route to delete a record.
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PagesController;

Route::get('/', [PagesController::class, 'datatableindex'])->name('datatableindex');
Route::get('/getdatatabledata', [PagesController::class, 'getDataTableData'])->name('getDataTableData');
Route::post('/getEmployeeData', [PagesController::class, 'getEmployeeData'])->name('getEmployeeData');
Route::post('/updateEmployee', [PagesController::class, 'updateEmployee'])->name('updateEmployee');
Route::post('/deleteEmployee', [PagesController::class, 'deleteEmployee'])->name('deleteEmployee');

6. Create View

Create index.blade.php file in views/ folder.

HTML

Store CSRF token in <meta > tag. Include jQuery, Bootstrap, and DataTable libraries.

Create a bootstrap modal to display edit form. Form fields auto-filled with data when clicking on the edit icon using jQuery AJAX.

Create <table id='empTable'> to initialize DataTable.


Script

Read CSRF token from <meta > tag and store in CSRF_TOKEN variable.

Initialize DataTable in #empTable. Set AJAX URL to route('getDataTableData') and specify keys name that needs to read in columns options.

  • Update –

Define click event on updateUser class. Read data-id attribute of the button and assign it to id variable. Update #txt_empid value with id variable.

Send AJAX request to route('getEmployeeData') and pass {_token: CSRF_TOKEN,id: id} as data to fetch a record and fill Bootstrap modal fields for the update.

Define click event on Bootstrap Modal save button #btn_save. Read all elements value and assign to the variables. If all elements has value then send AJAX request to route('updateEmployee') and pass {_token: CSRF_TOKEN,id: id,emp_name: emp_name, email: email, gender: gender, city: city} as data.

On successful callback check if response.success == 1. If it is means a record is updated successfully. Empty the Modal input element values and refresh the DataTable.

  • Delete –

Define click event on deleteUser class. Read data-id attribute of the button and assign it to id variable.

Send AJAX request to route('deleteEmployee') and pass {_token: CSRF_TOKEN,id: id} as data. On successful callback check if response.success == 1 . If it is means a record is deleted successfully and refresh the DataTable.

Completed Code

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <meta name="csrf-token" content="{{ csrf_token() }}">
   <title>How to add Edit Delete button in Yajra DataTables – Laravel</title>

   <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/css/bootstrap.min.css"/>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css"/>

</head>
<body>
   <div class='container mt-5'>

       <!-- Modal -->
       <div id="updateModal" class="modal fade" role="dialog">
           <div class="modal-dialog">

               <!-- Modal content-->
              <div class="modal-content">
                  <div class="modal-header">
                      <h4 class="modal-title">Update</h4>
                      <button type="button" class="close" data-dismiss="modal">&times;</button> 
                  </div>
                  <div class="modal-body">
                      <div class="form-group">
                          <label for="name" >Employee Name</label>
                          <input type="text" class="form-control" id="emp_name" placeholder="Enter Employee name" required> 
                      </div>
                      <div class="form-group">
                          <label for="email" >Email</label> 
                          <input type="email" class="form-control" id="email" placeholder="Enter email"> 
                      </div> 
                      <div class="form-group">
                          <label for="gender" >Gender</label>
                          <select id='gender' class="form-control">
                              <option value='Male'>Male</option>
                              <option value='Female'>Female</option>
                          </select> 
                      </div> 
                     <div class="form-group">
                          <label for="city" >City</label> 
                          <input type="text" class="form-control" id="city" placeholder="Enter city"> 
                     </div>

                  </div>
                  <div class="modal-footer">
                      <input type="hidden" id="txt_empid" value="0">
                      <button type="button" class="btn btn-success btn-sm" id="btn_save">Save</button>
                      <button type="button" class="btn btn-default btn-sm" data-dismiss="modal">Close</button>
                  </div>
             </div>

           </div>
       </div>

       <!-- Table -->
       <table id='empTable' class='datatable'>
           <thead >
               <tr>
                   <td>Employee Name</td>
                   <td>Email</td>
                   <td>Gender</td>
                   <td>City</td>
                   <td>Status</td>
                   <td>Action</td>
               </tr>
           </thead>
       </table>
   </div>

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
   <script type="text/javascript">
   // CSRF Token
   var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content'); 
   $(document).ready(function(){

       // Initialize
       var empTable = $('#empTable').DataTable({
             processing: true,
             serverSide: true,
             ajax: "{{ route('getDataTableData') }}",
             columns: [
                 { data: 'emp_name' },
                 { data: 'email' },
                 { data: 'gender' },
                 { data: 'city' },
                 { data: 'status' },
                 { data: 'action' },
             ]
       });

       // Update record
       $('#empTable').on('click','.updateUser',function(){
            var id = $(this).data('id');

            $('#txt_empid').val(id);

            // AJAX request
            $.ajax({
                url: "{{ route('getEmployeeData') }}",
                type: 'post',
                data: {_token: CSRF_TOKEN,id: id},
                dataType: 'json',
                success: function(response){

                    if(response.success == 1){

                         $('#emp_name').val(response.emp_name);
                         $('#email').val(response.email);
                         $('#gender').val(response.gender);
                         $('#city').val(response.city);

                         empTable.ajax.reload();
                    }else{
                         alert("Invalid ID.");
                    }
                }
            });

       });

       // Save user 
       $('#btn_save').click(function(){
            var id = $('#txt_empid').val();

            var emp_name = $('#emp_name').val().trim();
            var email = $('#email').val().trim();
            var gender = $('#gender').val().trim();
            var city = $('#city').val().trim();

            if(emp_name !='' && email != '' && city != ''){

                 // AJAX request
                 $.ajax({
                     url: "{{ route('updateEmployee') }}",
                     type: 'post',
                     data: {_token: CSRF_TOKEN,id: id,emp_name: emp_name, email: email, gender: gender, city: city},
                     dataType: 'json',
                     success: function(response){
                         if(response.success == 1){
                              alert(response.msg);

                              // Empty and reset the values
                              $('#emp_name','#email','#city').val('');
                              $('#gender').val('Male');
                              $('#txt_empid').val(0);

                              // Reload DataTable
                              empTable.ajax.reload();

                              // Close modal
                              $('#updateModal').modal('toggle');
                         }else{
                              alert(response.msg);
                         }
                     }
                 });

            }else{
                 alert('Please fill all fields.');
            }
       });

       // Delete record
       $('#empTable').on('click','.deleteUser',function(){
            var id = $(this).data('id');

            var deleteConfirm = confirm("Are you sure?");
            if (deleteConfirm == true) {
                 // AJAX request
                 $.ajax({
                     url: "{{ route('deleteEmployee') }}",
                     type: 'post',
                     data: {_token: CSRF_TOKEN,id: id},
                     success: function(response){
                          if(response.success == 1){
                               alert("Record deleted.");

                               // Reload DataTable
                               empTable.ajax.reload();
                          }else{
                                alert("Invalid ID.");
                          }
                     }
                 });
            }

       });

   });

   </script>
</body>
</html>

7. Output

View Output


8. Conclusion

You can similarly add more buttons or other HTML elements like – radio button, checkbox, textbox, etc. in the DataTables.

Make sure to redraw DataTables after performing action otherwise, changes not display in pagination.

If you found this tutorial helpful then don't forget to share.

Original article source at: https://makitweb.com/

#laravel #button 

Add Edit Delete Button in Yajra DataTables in Laravel
Nat  Grady

Nat Grady

1669816920

How to Create an HTML Button Programmatically with JavaScript

JavaScript programmatically create an HTML button

Sometimes you need to create an HTML button programmatically as a result of some code execution. You can easily create a button using JavaScript by calling on the document.createElement("button") method.

For example, let’s create a <button> that says "Click Me" using JavaScript:

  • First, you call the document.createElement("button") and assign the returned element to a variable named btn.
  • Then, assign the "Click Me" string to the btn.innerHTML property
  • Finally, use document.body.appendChild() to append the button element to the <body> tag

The code below shows how this can be done:

let btn = document.createElement("button");
btn.innerHTML = "Click Me";
document.body.appendChild(btn);

You can append the button element that you’ve created with JavaScript anywhere inside your HTML page by using the appendChild() method.

You can also set the button’s name, type, or value attributes as required by your project. Sometimes, you need to create a type='submit' button for forms:

let btn = document.createElement("button");
btn.innerHTML = "Submit";
btn.type = "submit";
btn.name = "formBtn";
document.body.appendChild(btn);

The code above will create the following HTML <button> tag:

<button type="submit" name="formBtn">
  Submit
</button>

Finally, if you want to execute some code when the button is clicked, you can change the onclick property to call a function as follows:

let btn = document.createElement("button");
btn.innerHTML = "Save";
btn.onclick = function () {
  alert("Button is clicked");
};
document.body.appendChild(btn);

or you can also add an event listener as follows:

let btn = document.createElement("button");
btn.innerHTML = "Save";
btn.addEventListener("click", function () {
  alert("Button is clicked");
});
document.body.appendChild(btn);

And that’s how you can create a button programmatically using JavaScript.

Original article source at: https://sebhastian.com/

#javascript #html #button 

How to Create an HTML Button Programmatically with JavaScript
Mike  Kozey

Mike Kozey

1668614609

How to Disable Button Tutorial in React

React: How to disable button tutorial

Here's how you disable a button using React


When you need to disable a button using React, you can simply add the disabled prop to your <button> element:

function App() {
  return <button disabled={true}>Click me!</button>;
}

Knowing this, you can easily modify the code according to your requirements to disable the <button>.

React disable button after click

For example, you may want to disable a <button> after it has been clicked. You can do so by adding a state that controls the value of disabled prop. Let’s name the state disable and set its default value to false:

const [disable, setDisable] = React.useState(false);

After that, you need to use the disable state value as the value of disabled prop in the <button> element.

Finally, add an onClick prop to the <button> element that will set the disable state to true.

The full code is as shown below:

import React from "react";
function App() {
  const [disable, setDisable] = React.useState(false);

  return (
    <button disabled={disable} onClick={() => setDisable(true)}>
      Click me!
    </button>
  );
}

With the code above, your button will be disabled once it receives a click event.

React disable button for login form

In another example, you may have a login button that you want to disable as long as the email and password <input> is empty.

You can easily do so by checking controlling the value of both <input> elements using the state.

When the value of email or password state is empty, the disabled prop value must be true. You can do so by using the following code:

disabled={!email || !password}

The following code example shows how to do it:

import React, { useState } from "react";

function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleEmailChange = (event) => {
    setEmail(event.target.value);
  };

  const handlePasswordChange = (event) => {
    setPassword(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`Your state values: \n 
            email: ${email} \n 
            password: ${password} \n 
            You can replace this alert with your process`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Email address</label>
        <input
          type="email"
          name="email"
          placeholder="Enter email"
          onChange={handleEmailChange}
          value={email}
        />
      </div>
      <div>
        <label>Password</label>
        <input
          type="password"
          name="password"
          placeholder="Enter password"
          onChange={handlePasswordChange}
          value={password}
        />
      </div>
      <button type="submit" disabled={!email || !password}>
        Login
      </button>
    </form>
  );
}

This way, your <button> element will be disabled as long as the value of email or password state is falsy

Conclusion

To conclude, you can disable a <button> element in React by setting the disabled prop to true.

Depending on the conditions required to disable the <button>, you can manipulate the disabled prop through various ways, such as by checking if the form values are empty or the <button> has been clicked by the user.

Original article source at: https://sebhastian.com/

#react #disable #button 

How to Disable Button Tutorial in React

Bouncing Button Animation In Flutter

any_animated_button

Very often after tapping a button we send some data or form to remote API and we need to signalize it to the user. This package makes it easy for us by creating expandable AnyAnimatedButton and AnyAnimatedButtonBloc.

Easy usage

AnyAnimatedButton depends on bloc pattern. To create custom button we need to create new bloc and
widget.

AnyAnimatedButtonBloc

We need to create class, which extends AnyAnimatedButtonBloc and override asyncAction.

AnyAnimatedButtonBloc<Input, Output, Failure> takes 3 generic types:

  • Input - type of the input data we want to send or process
  • Output - type of the output data we will receive from i.e. API
  • Failure - type of error returned from bloc when any error occurs. It helps you manage your error handling

The function we need to override depends on dartz Either, which return either a Failure or data of type Output and takes in an event with type Input.

Future<Either<Failure, Output>> asyncAction(Input input);

AnyAnimatedButton

AnyAnimatedButton is based on AnimatedContainer. To create our own button we need to create class, which extends CustomAnyAnimatedButton. CustomAnyAnimatedButton consists of 2 fields, which needs to be overridden:

  • bloc - AnyAnimatedButtonBloc? - bloc which should be connected with the button. If we won't pass it, the button won't animate
  • defaultParams - AnyAnimatedButtonParams - params object, which describes how button should look and behave

and 3 optional fields:

  • progressParams - AnyAnimatedButtonParams - params object for describing button in progress state
  • successParams - AnyAnimatedButtonParams - params object for describing button in success state
  • errorParams - AnyAnimatedButtonParams - params object for describing button in error state

AnyAnimatedButtonParams

The class that holds all the data about button look and behavior. All properties that we want to animate should be put directly inside all corresponding fields. Rest of them (like Text) should go to child field, which takes Widget.

Fields list:

Key? key;
AlignmentGeometry? alignment;
EdgeInsetsGeometry? padding;
Color? color;
Decoration? decoration;
Decoration? foregroundDecoration;
double? width;
double height;
BoxConstraints? constraints;
EdgeInsetsGeometry? margin;
Matrix4? transform;
AlignmentGeometry? transformAlignment;
Widget? child;
Clip clipBehavior;
Curve curve;
Duration duration;
VoidCallback? onEnd;

The only required field is height, rest of them are optional.

We have got also 3 factory constructors, which describe default progress, error and success button state. We can reuse them with changed colors and size.

factory AnyAnimatedButtonParams.progress({
  double? size,
  Color backgroundColor = Colors.blue,
  Color progressColor = Colors.white,
  EdgeInsets padding = const EdgeInsets.all(10.0),
  Duration duration = const Duration(milliseconds: 300),
})
factory AnyAnimatedButtonParams.success({
  double? size,
  Color backgroundColor = Colors.green,
  Color iconColor = Colors.white,
  EdgeInsets padding = const EdgeInsets.all(8.0),
  Duration duration = const Duration(milliseconds: 300),
})
factory AnyAnimatedButtonParams.error({
  double? size,
  Color backgroundColor = Colors.red,
  Color iconColor = Colors.white,
  EdgeInsets padding = const EdgeInsets.all(8.0),
  Duration duration = const Duration(milliseconds: 300),
})

Buttons width

There are 3 possible width behaviors:

  • double.infinity - the button expands as much as he can
  • null - the button is as small as it can - it fits its content
  • fixed - we can set fixed width i.e. 200 and the button will always be this wide

Splash effect

There is one problem with InkWell splash effect. If we want the splash effect to work we need to put in child field firstly Material with transparent color → InkWell → rest of the child.

@override
AnyAnimatedButtonParams get defaultParams => AnyAnimatedButtonParams(
  child: Material(
    color: Colors.transparent,
    child: InkWell(
      onTap: onTap,
      borderRadius: someBorderRadius,
      child: restOfTheButton,
    ),
  ),
);

AnyAnimatedButtonBlocListener

The package has built-in BlocListener, which makes it easier for you to listen to the state changes. AnyAnimatedButtonBlocListener<Input, Output, Failure> takes 3 generic types,Input is type of data that goes into the bloc, Output is type of data returned on success and Failure is the error which will be returned, when any error occurs in bloc. It does not take child argument, so it should be put in MultiBlocListener.

AnyAnimatedButtonBlocListener<int, double, Failure>(
  bloc: _successBloc,
  onDefault: () {
    print('Default state');
  },
  onProgressStart: () {
    print('Progress state starts');
  },
  onProgressEnd: () {
    print('Progress state ends');
  },
  onSuccessStart: (value) {
   print('Value: $value');
  },
  onSuccessEnd: (value) {
   print('Value: $value');
  },
  onErrorStart: (failure) {
    print('Error state starts');
  },
  onErrorEnd: (failure) {
    print('Error state ends');
  },
),

Examples

My way of handling errors is to create abstract class Failure and extending it for every possible error place.

abstract class Failure extends Equatable {
  @override
  List<Object> get props => [];

  String get errorMessage => 'error';
}

class DefaultFailure extends Failure {}

All of the examples beneath are made based on only 1 button class:

class MinimalisticButton extends CustomAnyAnimatedButton {
  MinimalisticButton({
    required this.onTap,
    required this.text,
    this.enabled = true,
    this.width,
    this.bloc,
  });

  @override
  final AnyAnimatedButtonBloc? bloc;
  final VoidCallback onTap;
  final String text;
  final bool enabled;
  final double? width;

  final BorderRadius _borderRadius = BorderRadius.circular(22.0);

  @override
  AnyAnimatedButtonParams get defaultParams => AnyAnimatedButtonParams(
        width: width,
        height: 56.0,
        decoration: BoxDecoration(
          color: enabled ? Colors.blue : Colors.grey,
          borderRadius: _borderRadius,
        ),
        child: Material(
          color: Colors.transparent,
          child: InkWell(
            onTap: enabled ? onTap : null,
            borderRadius: _borderRadius,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    text,
                    style: const TextStyle(color: Colors.white),
                    maxLines: 1,
                    softWrap: false,
                  ),
                ],
              ),
            ),
          ),
        ),
      );
}

and 3 bloc classes

_successBloc = SuccessBloc();
_success2Bloc = SuccessBloc();
_errorBloc = ErrorBloc();
_shortBloc = ShortBloc();
_enabledButton = ShortBloc();
_nullWidth = ShortBloc();
_infinityWidth = ShortBloc();
_fixedWidth = ShortBloc();
class SuccessBloc extends AnyAnimatedButtonBloc<int, double, Failure> {
  @override
  Future<Either<Failure, double>> asyncAction(int input) {
    return Future.delayed(
      const Duration(milliseconds: 2000),
      () => Right(input * 10.0),
    );
  }
}
class ErrorBloc extends AnyAnimatedButtonBloc<int, String, Failure> {
  @override
  Future<Either<Failure, String>> asyncAction(int input) {
    return Future.delayed(
      const Duration(milliseconds: 2000),
      () => Left(DefaultFailure()),
    );
  }
}
class ShortBloc extends AnyAnimatedButtonBloc<int, String, Failure> {
  @override
  Future<Either<Failure, String>> asyncAction(int input) {
    return Future.delayed(
      const Duration(milliseconds: 50),
      () => Left(DefaultFailure()),
    );
  }
}

Button with no bloc (not animating)

MinimalisticButton(
  text: 'Non animated button',
  onTap: () {},
),

Animated button with success outcome

MinimalisticButton(
  bloc: _successBloc,
  text: 'Animated success button',
  onTap: () => _successBloc.add(TriggerAnyAnimatedButtonEvent(13)),
),

Animated button with error outcome

MinimalisticButton(
  bloc: _errorBloc,
  text: 'Animated error button',
  onTap: () => _errorBloc.add(TriggerAnyAnimatedButtonEvent(13)),
),

Animated button with short loading state

MinimalisticButton(
  bloc: _shortBloc,
  text: 'Short animation button',
  onTap: () => _shortBloc.add(TriggerAnyAnimatedButtonEvent(13)),
),

Animated button with enabling functionality

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    MinimalisticButton(
      bloc: _enabledButton,
      text: 'Enabled button',
      enabled: _enabled,
      onTap: () => _enabledButton.add(TriggerAnyAnimatedButtonEvent(13)),
    ),
    const SizedBox(width: 12.0),
    MinimalisticButton(
      text: _enabled ? '<- disable' : '<- enable',
      onTap: () {
        setState(() {
          _enabled = !_enabled;
        });
      },
    ),
  ],
),

Animated button with width: null

MinimalisticButton(
  bloc: _nullWidth,
  text: 'width: null',
  onTap: () => _nullWidth.add(TriggerAnyAnimatedButtonEvent(13)),
),

Animated button with width: double.infinity

MinimalisticButton(
  bloc: _infinityWidth,
  width: double.infinity,
  text: 'width: double.infinity',
  onTap: () => _infinityWidth.add(TriggerAnyAnimatedButtonEvent(13)),
),

Animated button with fixed width: 200.0

MinimalisticButton(
  bloc: _fixedWidth,
  width: 200.0,
  text: 'width: 200.0',
  onTap: () => _fixedWidth.add(TriggerAnyAnimatedButtonEvent(13)),
),

Known bugs

  • updating text on button with width set to null does not work properly. The button width will adjust only to the first text width. The workaround is to set fixed width of the longer text instead of null.

Created by Piotr Białas, appvinio

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add any_animated_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  any_animated_button: ^0.0.3

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:any_animated_button/any_animated_button.dart'; 

example/lib/main.dart

import 'package:example/home_screen.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: HomeScreen(),
    );
  }
} 

Download Details:

Author: appvinio

Source Code: https://github.com/appvinio/any_animated_button

#flutter #animations #button 

Bouncing Button Animation In Flutter
Rupert  Beatty

Rupert Beatty

1667550720

Floaty: Floating Action Button for iOS

Floaty 

Floaty is simple floating action button for iOS. (formerly KCFloatingActionButton)

Why change the name?

  1. Follow the swift naming convention.
  2. KCFloatingActionButton is too long.

Preview

Preview gif

Requirements

  • iOS 10.0+
  • Swift 5.0

Installation

CocoaPods

use_frameworks!
pod 'Floaty', '~> 4.2.0'

Carthage

github "kciter/Floaty"

Swift Package Manager

Once you have your Swift package set up, adding Floaty as a dependency is as easy as adding it to the dependencies value of your Package.swift.

dependencies: [
    .package(url: "https://github.com/kciter/Floaty.git", from: "4.2.1")
]

Manually

To install manually the Floaty in an app, just drag the Floaty/*.swift file into your project.

Usage

Storyboard support

Storyboard support1 Storyboard support2

Dependent on the UIWindow.

Floaty.global.button.addItem(title: "Hello, World!")
Floaty.global.show()

Dependent on the UIWindow

Dependent on the UIViewController.

let floaty = Floaty()
floaty.addItem(title: "Hello, World!")
self.view.addSubview(floaty)

Dependent on the UIViewController

Use icon

let floaty = Floaty()
floaty.addItem("Hello, World!", icon: UIImage(named: "icon")!)
self.view.addSubview(floaty)

Use icon

Use handler

Swift

let floaty = Floaty()
floaty.addItem("I got a handler", icon: UIImage(named: "icon")!, handler: { item in
    let alert = UIAlertController(title: "Hey", message: "I'm hungry...", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Me too", style: .default, handler: nil))
    self.present(alert, animated: true, completion: nil)
    floaty.close()
})
self.view.addSubview(floaty)

Use handler

Use custom item

let item = FloatyItem()
item.buttonColor = UIColor.blueColor()
item.title = "Custom item"
Floaty.global.button.addItem(item: item)

Use custom item

RTL Support

You can use the rtlMode property to mirror the Floaty Button for rtl languages.

Floaty.global.rtlMode = true

Rtl Enabled Rtl Disabled

Sticky

You can use the sticky property.

floaty.sticky = true // sticking to parent UIScrollView(also UITableView, UICollectionView)
scrollView.addSubview(floaty)

Friendly Tap

You can use the friendlyTap property.

fab.friendlyTap = true
scrollView.addSubview(fab)

With the default location of the frame, the button is now tappable until the right and rightbottom of the screen. This prevents tapping behind it by accident.

Animation type

PopFadeSlide Left
Pop animation gifFade animation gifSlide left animation gif
Slide UpNone 
Slide up animation gifNone animation gif 

ToDo

  •  Labels to come at the right hand side of the FAB Item menu.

Download Details:

Author: kciter
Source Code: https://github.com/kciter/Floaty 
License: MIT license

#swift #ios #components #action #button 

Floaty: Floating Action Button for iOS

A Material Flutter Button That Supports Variety of Button Styles

progress_loading_button

progress_loading_button is a free and open source (MIT license) Material Flutter Button that supports variety of buttons style demands. It is designed to be easy to use and customizable.

Get started

Add this to your package's pubspec.yaml file:

progress_loading_button: '^1.0.0'

Install it

You can install packages from the command line:

$ flutter pub get

Alternatively, your editor might support flutter pub get.

Import it

Now in your Dart code, you can use:

import 'package:progress_loading_button/progress_loading_button.dart';

How to use

Add LoadingButton to your widget tree:

LoadingButton(
    defaultWidget: Text('Click Me'),
    width: 196,
    height: 60,
    onPressed: () async {
        await Future.delayed(
            Duration(milliseconds: 3000),
            () {
                print('Button Pressed');
            },
        );
    },
)

More parameters:

LoadingButton({
    Key? key,
    required this.defaultWidget,
    this.loadingWidget = const CircularProgressIndicator(),
    required this.onPressed,
    this.type = LoadingButtonType.Raised,
    this.color,
    this.width = double.infinity,
    this.height = 40.0,
    this.borderRadius = 5.0,
    this.borderSide = BorderSide.none,
    this.animate = true,
  }) : super(key: key);

Three types supported:

enum LoadingButtonType {
  Raised,
  Flat,
  Outline,
}

Example

Source

Source code and example of this library can be found in git:

$ git clone https://github.com/gairick-saha/progress_loading_button.git

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add progress_loading_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  progress_loading_button: ^1.1.4

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:progress_loading_button/progress_loading_button.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:progress_loading_button/progress_loading_button.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text('Progress Loading Button Example'),
        ),
        body: Center(
          child: LoadingButton(
            defaultWidget: const Text('Click Me'),
            width: 196,
            height: 60,
            onPressed: () async {
              await Future.delayed(
                const Duration(milliseconds: 3000),
                () {
                  print('Button Pressed');
                },
              );
            },
          ),
        ),
      ),
    );
  }
} 

Download Details:

Author: gairick-saha

Source Code: https://github.com/gairick-saha/progress_loading_but

#flutter #button 

A Material Flutter Button That Supports Variety of Button Styles

A Flutter Plugin for Quick Use Of Some Pre-developed Buttons

A Flutter plugin for quick use of some pre-developed buttons. Especially social buttons, but they are totally customizable, so, in the end, for any use.

Installation

Add to pubspec.yaml.

dependencies:
...
buttons_showcase: ^0.0.4

Usage Example

import 'package:buttons_showcase/buttons_showcase.dart';

BaseButton class

class BaseButton extends StatelessWidget {
  BaseButton(
    {
      this.textCaps = false,
      this.showLogo = true,
      this.customText,
      this.size = "M",
      this.iconType = 0,
      this.customShape,
      this.function,
      required this.social,
    ) : super(key: key);
  }
...

Various different implementations:

BaseButton(size: "S", social: listSocial[keyword]!),
BaseButton(size: "M", social: listSocial[keyword]!),
BaseButton(size: "L", social: listSocial[keyword]!),
// MANAGE THE LOGO SECTION
BaseButton(showLogo: false, social: listSocial[keyword]!),
// MANAGE THE TEXT SECTION
BaseButton(customText: "Your custom text", social: listSocial[keyword]!),
// MANAGE THE SHAPE SECTION
BaseButton(customShape: "circle", social: listSocial[keyword]!),
BaseButton(customShape: "square", iconType: 1, social: listSocial[keyword]!)

The Social class

class Social {
  Social(this.name, this.color, this.textColor, this.logoPaths);

  String name;
  Color color, textColor;
  List<String> logoPaths;
}

Social example

Color githubColor = const Color(0xFF333333);
Color whiteColor = Colors.white;

Social(
  "GitHub",
  githubColor,
  whiteColor,
  [
    "assets/icons/github.png",
    "assets/icons/github_full.png",
    "assets/icons/github_outline.png"
  ]
)

The 'Example' contain the following buttons:

enum Socials {
  Amazon,
  Apple,
  Discord,
  Facebook,
  GitHub,
  Instagram,
  LinkedIn,
  Microsoft,
  Pinterest, 
  Snapchat,
  Spotify,
  Telegram,
  TikTok,
  Twitch,
  Twitter,
  WhatsApp,
  Yahoo
}

Additional information

Github repository: https://github.com/Fhyrel/buttons_showcase Feel free to ask, report issues and contribute in the development of my package.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add buttons_showcase

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  buttons_showcase: ^0.0.4

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:buttons_showcase/buttons_showcase.dart'; 

example/lib/main.dart

/// Copyright (c) 2022 Ivan Territo
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.

import 'package:example/pages/homepage.dart';
import 'package:flutter/material.dart';

/// Buttons Showcase main page
void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Buttons Showcase',
      theme: ThemeData(
        primarySwatch: Colors.pink,
      ),
      home: const Homepage(),
    );
  }
} 

Download Details:

Author: 

Source Code: https://pub.dev/packages/buttons_showcase

#flutter #button 

A Flutter Plugin for Quick Use Of Some Pre-developed Buttons

A Convenient Way to Quickly Create Buttons in Flutter Development

idkit_button

This package mainly deals with the convenient construction of button components that interact with users in the development of the flutter project.

Features included in this package

Text button

factory IDKitButton.title(...) -> IDKitButton

Image button

factory IDKitButton.image(...) -> IDKitButton

Image and text button

factory IDKitButton.imageAndText(...) -> IDKitButton

Cut corner type button

factory IDKitButton.corner(...) -> IDKitButton

Gradient type button

factory IDKitButton.gradient(...) -> IDKitButton

Border type button

factory IDKitButton.outline(...) -> IDKitButton

Custom type button

const IDKitButton(...) -> IDKitButton

The package function example demonstration

Text button

IDKitButton.title(
  'Next',
  height: 44,
  width: 300,
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(8),
    color: Colors.blue,
  ),
  onTap: () {
    print('Button on click!');
  },
)

Image button

IDKitButton.image(
  imgpath,
  width: 100,
  bgColor: Colors.red,
  onTap: () {
    print('Button on click!');
  },
),

Image and text button

IDKitButton.imageAndText(
  imgpath,
  'Setup',
  height: 120,
  imgSize: const Size(100, 200),
  bgColor: Colors.blue,
  onTap: () {
    print('Button on click!');
  },
)

Cut corner type button

IDKitButton.corner(
  bgColor: Colors.blue,
  height: 60,
  width: 100,
  onTap: () {
    print('Button on click!');
  },
)

Gradient type button

IDKitButton.gradient(
  const <Color>[Colors.red, Colors.green],
  width: 200,
  height: 60,
  title: 'Finish',
  onTap: () {
    print('Button on click!');
  },
)

Border type button

IDKitButton.outline(
  title: 'Border Button',
  padding: const EdgeInsets.all(20),
  onTap: () {
    print('Button on click!');
  },
)

Custom type button

IDKitButton(
  decoration: BoxDecoration(
      image: DecorationImage(
      image: NetworkImage(imgpath),
      fit: BoxFit.fill,
      ),
  ),
  title: 'Backgrount button',
  height: 60,
)

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add idkit_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  idkit_button: ^0.0.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:idkit_button/idkit_button.dart'; 

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:idkit_button/idkit_button.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final String imgpath = 'https://img0.baidu.com/it/u=2137484864,1681562941&fm=26&fmt=auto';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        children: <Widget>[
          IDKitButton.title(
            'Next',
            bgColor: Colors.blue,
            height: 44,
            enable: false,
            onTap: () {
              print('Button on click!');
            },
          ),
          const SizedBox(height: 10),
          IDKitButton.title(
            'Next',
            height: 44,
            width: 300,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: Colors.blue,
            ),
            onTap: () {
              print('Button on click!');
            },
          ),
          const SizedBox(height: 10),
          IDKitButton.image(
            imgpath,
            width: 100,
            bgColor: Colors.red,
            onTap: () {
              print('Button on click!');
            },
          ),
          const SizedBox(height: 10),
          IDKitButton.imageAndText(
            imgpath,
            'Setup',
            height: 120,
            imgSize: const Size(100, 200),
            bgColor: Colors.blue,
            onTap: () {
              print('Button on click!');
            },
          ),
          const SizedBox(height: 10),
          IDKitButton.corner(
            bgColor: Colors.blue,
            height: 60,
            width: 100,
            onTap: () {
              print('Button on click!');
            },
          ),
          const SizedBox(height: 10),
          IDKitButton.gradient(
            const <Color>[Colors.red, Colors.green],
            width: 200,
            height: 60,
            title: 'Finish',
            onTap: () {
              print('Button on click!');
            },
          ),
          const SizedBox(height: 10),
          IDKitButton.outline(
            title: 'Border Button',
            padding: const EdgeInsets.all(20),
            onTap: () {
              print('Button on click!');
            },
          ),
          const SizedBox(height: 10),
          IDKitButton(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: NetworkImage(imgpath),
                fit: BoxFit.fill,
              ),
            ),
            title: 'Backgrount button',
            height: 60,
          ),
        ],
      ),
    );
  }
} 

Download Details:

Author: zhoushuangjian001

Source Code: https://github.com/zhoushuangjian001/idkit_button

#flutter #button 

A Convenient Way to Quickly Create Buttons in Flutter Development

A Customizable Progress Button Widget for Flutter android, IOS and Web

Progress State Button

A customizable progress button for Flutter

Test with DartPad

Installation

https://pub.dev/packages/progress_state_button

progress_state_button: "^1.0.4"

Usage

Icon

ProgressButton.icon(iconedButtons: {
      ButtonState.idle:
        IconedButton(
            text: "Send",
            icon: Icon(Icons.send,color: Colors.white),
            color: Colors.deepPurple.shade500),
      ButtonState.loading:
        IconedButton(
            text: "Loading",
            color: Colors.deepPurple.shade700),
      ButtonState.fail:
        IconedButton(
            text: "Failed",
            icon: Icon(Icons.cancel,color: Colors.white),
            color: Colors.red.shade300),
      ButtonState.success:
        IconedButton(
            text: "Success",
            icon: Icon(Icons.check_circle,color: Colors.white,),
            color: Colors.green.shade400)
    }, 
    onPressed: onPressed,
    state: ButtonState.idle);

With Custom Widgets

ProgressButton(
      stateWidgets: {
        ButtonState.idle: Text("Idle",style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),),
        ButtonState.loading: Text("Loading",style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),),
        ButtonState.fail: Text("Fail",style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),),
        ButtonState.success: Text("Success",style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),)
      },
      stateColors: {
        ButtonState.idle: Colors.grey.shade400,
        ButtonState.loading: Colors.blue.shade300,
        ButtonState.fail: Colors.red.shade300,
        ButtonState.success: Colors.green.shade400,
      },
      onPressed: onPressed,
      state: ButtonState.idle,
    );

Constructors

Default constructor of ProgressButton

stateWidgets - Widgets of states
stateColors - Background color oof states
state = ButtonState.idle` - Current state of button
onPressed - onPressed function same like MaterialButton
onAnimationEnd - onAnimatedEnd function calls like that onAnimatedEnd(AnimationStatus animationStatus,ButtonState currentState).
minWidth = 200.0 - Loading state width
maxWidth = 400.0 - failed,success,idle states width
radius = 16.0 - Button radius
height = 53.0 - Button height
circularProgressIndicator - CircularProgressIndicator widget, default is instating with current state color.
progressIndicatorAlignment = MainAxisAlignment.spaceBetween` - ProgressIndicator aligment
progressIndicatorSize = 35.0 - size of progress indicator
padding = EdgeInsets.zero - Padding of button
minWidthStates = List of min width states, loading is the default. If you want to make small only icon states define them on this.
animationDuration = Transition animation duration.

ProgressButton.icon() specific constructors

Map<ButtonState, IconedButton> iconedButtons- State and IconedButton map
double iconPadding: 4.0 - Padding of icon 
TextStyle textStyle - TextStyle of all of states

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add progress_state_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  progress_state_button: ^1.0.4

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:progress_state_button/iconed_button.dart';
import 'package:progress_state_button/progress_button.dart'; 

example/lib/main.dart

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:progress_state_button/iconed_button.dart';
import 'package:progress_state_button/progress_button.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Progress Button',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ProgressButtonHomePage(title: 'Progress Button'),
    );
  }
}

class ProgressButtonHomePage extends StatefulWidget {
  ProgressButtonHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _ProgressButtonHomePageState createState() => _ProgressButtonHomePageState();
}

class _ProgressButtonHomePageState extends State<ProgressButtonHomePage> {
  ButtonState stateOnlyText = ButtonState.idle;
  ButtonState stateOnlyCustomIndicatorText = ButtonState.idle;
  ButtonState stateTextWithIcon = ButtonState.idle;
  ButtonState stateTextWithIconMinWidthState = ButtonState.idle;

  Widget buildCustomButton() {
    var progressTextButton = ProgressButton(
      stateWidgets: {
        ButtonState.idle: Text(
          "Idle",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.loading: Text(
          "Loading",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.fail: Text(
          "Fail",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.success: Text(
          "Success",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        )
      },
      stateColors: {
        ButtonState.idle: Colors.grey.shade400,
        ButtonState.loading: Colors.blue.shade300,
        ButtonState.fail: Colors.red.shade300,
        ButtonState.success: Colors.green.shade400,
      },
      onPressed: onPressedCustomButton,
      state: stateOnlyText,
      padding: EdgeInsets.all(8.0),
    );
    return progressTextButton;
  }

  Widget buildCustomProgressIndicatorButton() {
    var progressTextButton = ProgressButton(
      stateWidgets: {
        ButtonState.idle: Text(
          "Idle",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.loading: Text(
          "Loading",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.fail: Text(
          "Fail",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        ),
        ButtonState.success: Text(
          "Success",
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.w500),
        )
      },
      progressIndicator:  CircularProgressIndicator( backgroundColor: Colors.white, valueColor: AlwaysStoppedAnimation(Colors.red), strokeWidth: 1, ),
      stateColors: {
        ButtonState.idle: Colors.grey.shade400,
        ButtonState.loading: Colors.blue.shade300,
        ButtonState.fail: Colors.red.shade300,
        ButtonState.success: Colors.green.shade400,
      },
      onPressed: onPressedCustomIndicatorButton,
      state: stateOnlyCustomIndicatorText,
      padding: EdgeInsets.all(8.0),
    );
    return progressTextButton;
  }

  Widget buildTextWithIcon() {
    return ProgressButton.icon(iconedButtons: {
      ButtonState.idle: IconedButton(
          text: "Send",
          icon: Icon(Icons.send, color: Colors.white),
          color: Colors.deepPurple.shade500),
      ButtonState.loading:
          IconedButton(text: "Loading", color: Colors.deepPurple.shade700),
      ButtonState.fail: IconedButton(
          text: "Failed",
          icon: Icon(Icons.cancel, color: Colors.white),
          color: Colors.red.shade300),
      ButtonState.success: IconedButton(
          text: "",
          icon: Icon(
            Icons.check_circle,
            color: Colors.white,
          ),
          color: Colors.green.shade400)
    }, onPressed: onPressedIconWithText, state: stateTextWithIcon);
  }

  Widget buildTextWithIconWithMinState() {
    return ProgressButton.icon(
      iconedButtons: {
        ButtonState.idle: IconedButton(
            text: "Send",
            icon: Icon(Icons.send, color: Colors.white),
            color: Colors.deepPurple.shade500),
        ButtonState.loading:
            IconedButton(text: "Loading", color: Colors.deepPurple.shade700),
        ButtonState.fail: IconedButton(
            text: "Failed",
            icon: Icon(Icons.cancel, color: Colors.white),
            color: Colors.red.shade300),
        ButtonState.success: IconedButton(
            icon: Icon(
              Icons.check_circle,
              color: Colors.white,
            ),
            color: Colors.green.shade400)
      },
      onPressed: onPressedIconWithMinWidthStateText,
      state: stateTextWithIconMinWidthState,
      minWidthStates: [ButtonState.loading, ButtonState.success],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            buildCustomButton(),
            Container(
              height: 32,
            ),
            buildTextWithIcon(),
            Container(
              height: 32,
            ),
            buildTextWithIconWithMinState(),
            Container(height: 32,),
            buildCustomProgressIndicatorButton()
          ],
        ),
      ),
    );
  }

  void onPressedCustomButton() {
    setState(() {
      switch (stateOnlyText) {
        case ButtonState.idle:
          stateOnlyText = ButtonState.loading;
          break;
        case ButtonState.loading:
          stateOnlyText = ButtonState.fail;
          break;
        case ButtonState.success:
          stateOnlyText = ButtonState.idle;
          break;
        case ButtonState.fail:
          stateOnlyText = ButtonState.success;
          break;
      }
    });
  }

  void onPressedCustomIndicatorButton() {
    setState(() {
      switch (stateOnlyCustomIndicatorText) {
        case ButtonState.idle:
          stateOnlyCustomIndicatorText = ButtonState.loading;
          break;
        case ButtonState.loading:
          stateOnlyCustomIndicatorText = ButtonState.fail;
          break;
        case ButtonState.success:
          stateOnlyCustomIndicatorText = ButtonState.idle;
          break;
        case ButtonState.fail:
          stateOnlyCustomIndicatorText = ButtonState.success;
          break;
      }
    });
  }


  void onPressedIconWithText() async {
    switch (stateTextWithIcon) {
      case ButtonState.idle:
        stateTextWithIcon = ButtonState.loading;
        Future.delayed(Duration(seconds: 1), () {
          setState(() {
            stateTextWithIcon = Random.secure().nextBool()
                ? ButtonState.success
                : ButtonState.fail;
          });
        });

        break;
      case ButtonState.loading:
        break;
      case ButtonState.success:
        stateTextWithIcon = ButtonState.idle;
        break;
      case ButtonState.fail:
        stateTextWithIcon = ButtonState.idle;
        break;
    }
    setState(() {
      stateTextWithIcon = stateTextWithIcon;
    });
  }

  void onPressedIconWithMinWidthStateText() {
    switch (stateTextWithIconMinWidthState) {
      case ButtonState.idle:
        stateTextWithIconMinWidthState = ButtonState.loading;
        Future.delayed(Duration(seconds: 1), () {
          setState(() {
            stateTextWithIconMinWidthState = Random.secure().nextBool()
                ? ButtonState.success
                : ButtonState.fail;
          });
        });

        break;
      case ButtonState.loading:
        break;
      case ButtonState.success:
        stateTextWithIconMinWidthState = ButtonState.idle;
        break;
      case ButtonState.fail:
        stateTextWithIconMinWidthState = ButtonState.idle;
        break;
    }
    setState(() {
      stateTextWithIconMinWidthState = stateTextWithIconMinWidthState;
    });
  }
} 

Download Details:

Author: slm

Source Code: https://github.com/slm/progress-state-button/issues

#flutter #android #button 

A Customizable Progress Button Widget for Flutter android, IOS and Web
Monty  Boehm

Monty Boehm

1662555916

7 Best React Floating Button Libraries

In today's post we will learn about 7 Best React Floating Button Libraries. 

React Native doesn’t come with any FAB component built-in. A floating action button (FAB) is used whenever you want to display a button on the top of everything. If you have used ScrollView and the user can scroll up and down, this FAB button will always stay at the same position and doesn’t move with the scrolling. You can make this button in a circle or in a square shape. You can put icons or text in the middle.

1 - React-tiny-fab

A tiny Floating Action Button for React

Install

npm install react-tiny-fab
yarn add react-tiny-fab

react-tiny-fab v3 and up now relies on React version 16.8 and up because it is implemented using React Hooks

Usage

There are two components available for import - Fab and Action. You import them like this:

import { Fab, Action } from 'react-tiny-fab';
import 'react-tiny-fab/dist/styles.css';

View on Github

2 - React-floating-button-menu

A customizable floating action button menu that follows material design

Install

npm install --save react-floating-button-menu

Usage

You can customize opening direction, speed, and styles of each button via props. Other options will be added soon

import {
  FloatingMenu,
  MainButton,
  ChildButton,
  Directions
} from 'react-floating-button-menu';
import MdAdd from '@material-ui/icons/add';
import MdClose from '@material-ui/icons/clear';
import MdFavorite from '@material-ui/icons/favorite';


state = {
  isOpen: false,
}
...
  <FloatingMenu
    slideSpeed={500}
    direction={Directions.Up}
    spacing={8}
    isOpen={this.state.isOpen}
  >
    <MainButton
      iconResting={<MdAdd style={{ fontSize: 20 }} nativeColor="white" />}
      iconActive={<MdClose style={{ fontSize: 20 }} nativeColor="white" />}
      background="black"
      onClick={() => this.setState({ isOpen: !this.state.isOpen })}
      size={56}
    />
     <ChildButton
      icon={<MdFavorite style={{ fontSize: 20 }} />}
      background="white"
      size={40}
      onClick={() => console.log('First button clicked')}
    />
    <ChildButton
      icon={<MdFavorite style={{ fontSize: 20 }} />}
      background="white"
      size={40}
    />
    <ChildButton
      icon={<MdFavorite style={{ fontSize: 20 }} />}
      background="white"
      size={40}
    />
  </FloatingMenu>
...

View on Github

3 - React-floating-action-button

A simple Android like FAB React component

Getting Started

First, You need to install It, just like You would do with any NPM package:

npm i --save react-floating-action-button

Then, You need to import the library components within your own component

import React from 'react'
import { Container, Button, Link } from 'react-floating-action-button'

You can now start using the FAB components!

export default const YourAwesomeComponent = () => {
    return (
        <Container>
            <Link href="#"
                tooltip="Create note link"
                icon="far fa-sticky-note" />
            <Link href="#"
                tooltip="Add user link"
                icon="fas fa-user-plus" />
                className="fab-item btn btn-link btn-lg text-white"
            <Button
                tooltip="The big plus button!"
                icon="fas fa-plus"
                rotate={true}
                onClick={() => alert('FAB Rocks!')} />
        </Container>
    )
}

View on Github

4 - React Material Floating Button

Material floating action button implemented as a React component

Made to be fast and easy to customize. Shamelessly inspired by action buttons from Google Inbox, Evernote and Path.

Clone/download the repo from Github or just use npm:

npm install react-mfb --save

Docs are still to come (but hopefully will be there soon). In the meantime if you want to play with it check the project homepage source code for hints on how to use the component.

View on Github

5 - React-mui-speeddial

A Speed dial component for Material-UI

Installation

npm i --save react-mui-speeddial

Usage

import { SpeedDial, SpeedDialItem } from 'react-mui-speeddial';

// just some icons for illustration (example only):
import ContentAdd from 'material-ui/svg-icons/content/add';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import NewGameIcon from 'material-ui/svg-icons/av/playlist-add';
import NewPageIcon from 'material-ui/svg-icons/action/note-add';


render() {
  return (
    <SpeedDial
      fabContentOpen={
        <ContentAdd />
      }
      fabContentClose={
        <NavigationClose />
      }
    >
    
      <SpeedDialItem
        label="new game"
        fabContent={<NewGameIcon/>}
        onTouchTap={this.startNewGame}
      />
      
      <SpeedDialItem
        label="new page"
        fabContent={<NewPageIcon/>}
        onTouchTap={this.startNewPage}
      />

    </SpeedDial>
  );
 }

View on Github

6 - React-floating-button

React Awesome Floating Button 👌

Install

With npm

npm install react-floating-button

With yarn

yarn add react-floating-button

Usage

import { FloatingButton, Item } from "react-floating-button";
import downloadIcon from "./assets/DOWNLOAD.svg";
import forwardIcon from "./assets/FORWARD.svg";

<FloatingButton>
  <Item
    imgSrc={downloadIcon}
    onClick={() => {
      console.log("callback function here");
    }}
  />
  <Item
    imgSrc={forwardIcon}
    onClick={() => {
      console.log("callback function here");
    }}
  />
</FloatingButton>;

View on Github

7 - React-floating-buttons

A lightweight (zero-dependency), customizable and animated ⚛️ react floating buttons

Install

npm install --save react-floating-buttons

Usage

import React, { Component } from 'react'

import FloatingButtons from 'react-floating-buttons'

import icon1 from  './assets/icon1.svg'
import icon2 from  './assets/icon2.svg'

class Example extends Component {

  this.buttonsList = [
    { onClick: ()=> alert('clicked icon1'), src: icon1 },
    { onClick: ()=> alert('clicked icon2'), src: icon2 },
  ]

  render() {
    return <FloatingButtons buttonType='plus' dimension={50} buttonsList={this.buttonsList}  top={'calc(50% - 25px)'} left={'5%'} direction="right" />
  }
}

View on Github

Thank you for following this article. 

Related videos:

React Native Tutorial - Floating Action Button - React Native

#react #floating #button 

7 Best React Floating Button Libraries
Hunter  Krajcik

Hunter Krajcik

1662485640

X_button: A Button That Can Support Multiple Styles, including Shadow

Getting Started

xbutton is a button that can support multiple styles, including shadow, shadow color, rounded corners, click color, normal text, icon, and custom components. Relying only on native controls, no third-party plug-ins, easy to use

How to use it.

Wrap(
                direction: Axis.horizontal,
                spacing: 12,
                runSpacing: 12,
                children: [
              XButton.text(
                text: "填充文本样式",
                onPressed: () {},
              ),
              XButton.text(
                buttonType: XButtonType.outlined,
                text: "描边文本样式",
                color: Colors.black,
                onPressed: () {},
              ),
              XButton.icon(
                  onPressed: () {},
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.white,
                    size: 32,
                  )),
              XButton.icon(
                  onPressed: () {},
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.black,
                    size: 32,
                  ),
                  buttonType: XButtonType.outlined),
              XButton.image(
                assets: "images/ic_pen.png",
                size: 32,
                onPressed: () {},
              ),
              XButton.image(
                assets: "images/ic_pen.png",
                size: 32,
                buttonType: XButtonType.outlined,
                onPressed: () {},
              ),
              XButton.text(
                buttonType: XButtonType.noBackground,
                text: "纯文字按钮",
                color: Colors.black,
                onPressed: () {},
              ),
              XButton.text(
                text: "直角填充文本",
                buttonShape: XButtonShape.rect,
                onPressed: () {},
              ),
              XButton.text(
                text: "自定义圆角填充文本",
                // buttonShape: XButtonShape.roundRect,
                borderRadius: BorderRadius.circular(32),
                buttonShape: XButtonShape.roundRect,
                onPressed: () {},
              ),
              XButton.icon(
                  onPressed: () {},
                  buttonShape: XButtonShape.circle,
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.white,
                    size: 32,
                  )),
              XButton.icon(
                  onPressed: () {},
                  buttonShape: XButtonShape.circle,
                  buttonType: XButtonType.noBackground,
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.black,
                    size: 32,
                  )),
              XButton.icon(
                  onPressed: () {},
                  buttonShape: XButtonShape.roundRect,
                  buttonType: XButtonType.noBackground,
                  borderRadius: BorderRadius.circular(32),
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.black,
                    size: 32,
                  )),
              XButton.text(
                buttonType: XButtonType.noBackground,
                borderRadius: BorderRadius.circular(32),
                text: "纯文字自定义圆角",
                color: Colors.black,
                onPressed: () {},
              ),
              XButton.text(
                text: "自定义水波纹",
                overlayColor: Colors.orangeAccent.withAlpha(200),
                onPressed: () {},
              ),
              XButton.text(
                buttonType: XButtonType.noBackground,
                borderRadius: BorderRadius.circular(32),
                overlayColor: Colors.orangeAccent.withAlpha(200),
                text: "自定义圆角及水波纹",
                color: Colors.black,
                onPressed: () {},
              ),
              XButton.icon(
                  overlayColor: Colors.orangeAccent.withAlpha(200),
                  onPressed: () {},
                  buttonShape: XButtonShape.circle,
                  buttonType: XButtonType.noBackground,
                  icon: Icon(
                    Icons.account_circle,
                    color: Colors.black,
                    size: 32,
                  )),
            ])

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add x_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  x_button: ^0.0.3

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:x_button/xbutton.dart';
import 'package:x_button/xbutton_style.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:x_button/xbutton.dart';
import 'package:x_button/xbutton_style.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: getTheme(),
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
            child: SingleChildScrollView(
          child: Wrap(
              direction: Axis.horizontal,
              spacing: 12,
              runSpacing: 12,
              children: [
                XButton.text(
                  text: "填充文本样式",
                  onPressed: () {},
                ),
                XButton.text(
                  minSize: Size(90, 80),
                  text: "自定义大小",
                  onPressed: () {},
                ),
                XButton.text(
                  buttonType: XButtonType.outlined,
                  text: "描边文本样式",
                  color: Colors.black,
                  onPressed: () {},
                ),
                XButton.icon(
                    onPressed: () {},
                    icon: Icon(
                      Icons.account_circle,
                      color: Colors.white,
                      size: 32,
                    )),
                XButton.icon(
                    onPressed: () {},
                    icon: Icon(
                      Icons.account_circle,
                      color: Colors.black,
                      size: 32,
                    ),
                    buttonType: XButtonType.outlined),
                XButton.image(
                  assets: "images/ic_pen.png",
                  size: 32,
                  onPressed: () {},
                ),
                XButton.image(
                  assets: "images/ic_pen.png",
                  size: 32,
                  buttonType: XButtonType.outlined,
                  onPressed: () {},
                ),
                Container(
                  child: XButton.image(
                    assets: "images/ic_pen.png",
                    size: 32,
                    buttonType: XButtonType.noBackground,
                    buttonShape: XButtonShape.circle,
                    padding: EdgeInsets.all(8),
                    onPressed: () {},
                  ),
                ),
                XButton.text(
                  buttonType: XButtonType.noBackground,
                  text: "纯文字按钮",
                  color: Colors.black,
                  onPressed: () {},
                ),
                XButton.text(
                  text: "直角填充文本",
                  buttonShape: XButtonShape.rect,
                  onPressed: () {},
                ),
                XButton.text(
                  text: "自定义圆角填充文本",
                  // buttonShape: XButtonShape.roundRect,
                  borderRadius: BorderRadius.circular(32),
                  buttonShape: XButtonShape.roundRect,
                  onPressed: () {},
                ),
                XButton.icon(
                    onPressed: () {},
                    buttonShape: XButtonShape.circle,
                    icon: Icon(
                      Icons.account_circle,
                      color: Colors.white,
                      size: 32,
                    )),
                XButton.icon(
                    onPressed: () {},
                    buttonShape: XButtonShape.circle,
                    buttonType: XButtonType.noBackground,
                    icon: Icon(
                      Icons.account_circle,
                      color: Colors.black,
                      size: 32,
                    )),
                XButton.icon(
                    onPressed: () {},
                    buttonShape: XButtonShape.roundRect,
                    buttonType: XButtonType.noBackground,
                    borderRadius: BorderRadius.circular(32),
                    icon: Icon(
                      Icons.account_circle,
                      color: Colors.black,
                      size: 32,
                    )),
                XButton.text(
                  buttonType: XButtonType.noBackground,
                  borderRadius: BorderRadius.circular(32),
                  text: "纯文字自定义圆角",
                  color: Colors.black,
                  onPressed: () {},
                ),
                XButton.text(
                  text: "自定义水波纹",
                  overlayColor: Colors.orangeAccent.withAlpha(200),
                  onPressed: () {},
                ),
                XButton.text(
                  buttonType: XButtonType.noBackground,
                  borderRadius: BorderRadius.circular(32),
                  overlayColor: Colors.orangeAccent.withAlpha(200),
                  text: "自定义圆角及水波纹",
                  color: Colors.black,
                  onPressed: () {},
                ),
                XButton.icon(
                    overlayColor: Colors.orangeAccent.withAlpha(200),
                    onPressed: () {},
                    buttonShape: XButtonShape.circle,
                    buttonType: XButtonType.noBackground,
                    icon: Icon(
                      Icons.account_circle,
                      color: Colors.black,
                      size: 32,
                    )),
                XButton(
                  child: Text(
                    "自定义子控件",
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),
                  buttonType: XButtonType.elevated,
                  buttonShape: XButtonShape.roundRect,
                  backgroundColor: Colors.red,
                  padding: EdgeInsets.symmetric(vertical: 8, horizontal: 32),
                  minSize: Size.zero,
                  borderRadius: BorderRadius.all(Radius.circular(32)),
                )
              ]),
        )),
      ),
    );
  }

  ThemeData getTheme() {
    return ThemeData(
        elevatedButtonTheme: ElevatedButtonThemeData(
            style: ButtonStyle(
                minimumSize: MaterialStateProperty.all(Size(180, 56)),
                elevation: MaterialStateProperty.all(2),
                backgroundColor: MaterialStateProperty.all(Colors.blueAccent),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12))),
                splashFactory: InkSplash.splashFactory)),
        outlinedButtonTheme: OutlinedButtonThemeData(
            style: ButtonStyle(
                minimumSize: MaterialStateProperty.all(Size(180, 56)),
                elevation: MaterialStateProperty.all(2),
                backgroundColor: MaterialStateProperty.all(Colors.white),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12))),
                side: MaterialStateProperty.all(BorderSide(
                    width: 1,
                    color: Colors.blueAccent,
                    style: BorderStyle.solid)),
                overlayColor: MaterialStateProperty.all(Colors.black12),
                splashFactory: InkSplash.splashFactory)),
        textButtonTheme: TextButtonThemeData(
            style: ButtonStyle(
                minimumSize: MaterialStateProperty.all(Size(180, 56)),
                elevation: MaterialStateProperty.all(0),
                backgroundColor: MaterialStateProperty.all(Colors.transparent),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12))),
                overlayColor: MaterialStateProperty.all(Colors.black12),
                splashFactory: InkSplash.splashFactory)));
  }
}

Download Details:

Author: xypmhxy
Source Code: https://github.com/xypmhxy/Flutter-XButton 
License: MIT license

#flutter #dart #button 

X_button: A Button That Can Support Multiple Styles, including Shadow

Vue Component for Numbers Input

@smartweb/vue-number-input

Vue component for numbers input.

  • Accessible: uses ARIA agreements (100% accessibility in lighthouse)
  • Use your keyboard to navigate and control
  • Use your mousewheel or touchpad to increase or descrease value
  • Flexible styling
  • Support custom controls through slots

Live Demo

Download

Use npm

npm i @smartweb/vue-number-input

Or via cdn

<script src="https://unpkg.com/@smartweb/vue-number-input/build/vue-number-input.umd.min.js"></script>

Configuration

Import and register in your component.vue file

import VueNumberInput from '@smartweb/vue-number-input';

export default {
    components: {
        VueNumberInput
    }
};

Use it in your template with v-model directive

<template>
    <div id="app">
        <VueNumberInput
            v-model="you_model"
            :min="0"
            :max="100"
        ></VueNumberInput>
    </div>
</template>

Or register it globally in your application entry point (main.js or as you called it)

import Vue from 'vue';
import VueNumberInput from '@smartweb/vue-number-input';
// Global registration of the component
Vue.component('vue-number-input', VueNumberInput);

new Vue({
    render: h => h(App)
}).$mount('#app');

Usage

You can bind following props for vue-input-number element

PropTypeDefault valueDescription
valueNumber0Defines a value for 'value' and 'aria-valuenow' attributes of  element.
minNumberNumber.MIN_SAFE_INTEGERMinimum value of the number range. Provides a value for 'aria-valuemin' attributes of  element.
maxNumberNumber.MAX_SAFE_INTEGERMaximum value of the number range. Provides a value for 'aria-valuemax' attributes of  element.
stepNumber1Incremental step
disabledBooleanfalseDefines a value for 'aria-disabled' and 'disabled' attributes of  element. Also disable controls buttons
readonlyBooleanfalseDefines a value for 'readonly' attribute of  element.
autofocusBooleanfalseDefines a value for 'autofocus' attribute of  element.
controlsPositionString'on edge'Acceptable values: 'on edges', 'left', right'. Defines position of control buttons.
inputClassString-Defines user's class for input element
buttonIncClassString-Defines user's class for increase button
buttonDecClassString-Defines user's class for decrease button

Example

<vue-number-input
    v-model="you_model"
    :value="50"
    :min="0"
    :max="100"
    :controlsPosition="'left'"
/>

For more examples visit demo page

Your own controls through slot

You can create your own controls and pass them to slots
Read more about slots in official docs

<vue-number-input
    class="custom-container"
    v-model="you_model"
    :inputClass="custom-input"
    :buttonIncClass="custom-btn-inc"
    :buttonDecClass="custom-btn-dec"
>
    <!-- slot for decrease button -->
    <template #button-decrease>
        <custom-decrease-button></custom-decrease-button>
    </template>

    <!-- slot for increase button -->
    <template #button-increase>
        <custom-increase-button></custom-increase-button>
    </template>
</vue-number-input>

Events

EventDescriptionParams
inputTriggered on user input or buttons clicksNumber
changeTriggered on value changed and focus leave input elementNumber
focusTriggered when user focused on input fieldFocusEvent
blurTriggered when focus leave input fieldFocusEvent

LICENSE

The MIT License (MIT). Please see License File for more information.

Download Details:
 

Author: smwbtech
Download Link: Download The Source Code
Official Website: https://github.com/smwbtech/vue-number-input 
License: MIT license

#vue #javascript 

Vue Component for Numbers Input
Mike  Kozey

Mike Kozey

1659203160

Sticky_float_button: A Flutter Implementation Of Sticky Float Button

sticky_float_button

A Flutter implementation of sticky float button.

Getting started

In the pubspec.yaml of your flutter project, add the following dependency:

dependencies:
  ...
  sticky_float_button:

In your library add the following import:

import 'package:sticky_float_button/sticky_float_button.dart';

For help getting started with Flutter, view the online documentation.

Example

You can use 'Stack' to be located under 'Body' it.

 import 'package:flutter/material.dart';
 import 'package:sticky_float_button/sticky_float_button.dart';
 
 void main() {
   runApp(const MyApp());
 }
 
 class MyApp extends StatelessWidget {
   const MyApp({Key? key}) : super(key: key);
 
   @override
   Widget build(BuildContext context) {
     return MaterialApp(
       title: 'Flutter Sticky Float Button',
       theme: ThemeData(
         primarySwatch: Colors.blue,
       ),
       home: const StickyFloatExample(),
     );
   }
 }
 
 class StickyFloatExample extends StatefulWidget {
   const StickyFloatExample({Key? key}) : super(key: key);
 
   @override
   _StickyFloatExampleState createState() => _StickyFloatExampleState();
 }
 
 class _StickyFloatExampleState extends State<StickyFloatExample> {
   final StickyFloatButtonController _controller =
       StickyFloatButtonController(initPosition: Alignment.topRight);
 
   AppBar _appBar() {
     return AppBar(
       title: const Text("Sticky Float Example"),
     );
   }
 
   Widget _body() {
     return Center(
       child: GestureDetector(
           onTap: () {
             _controller.jumpToPosition(Alignment.center);
           },
           child: const Text("Sticky")),
     );
   }
 
   Widget _floatButton() {
     return StickyFloatButton(
       controller: _controller,
       child: const SingleFloatButton(
         child: CircleAvatar(
           backgroundColor: Colors.grey,
           child: Icon(
             Icons.add,
             color: Colors.white,
           ),
         ),
       ),
     );
   }
 
   @override
   Widget build(BuildContext context) {
     return Scaffold(
       appBar: _appBar(),
       body: Builder(
         builder: (context) {
           return Stack(
             children: [
               _body(),
               _floatButton(),
             ],
           );
         },
       ),
     );
   }
 }

You can find more examples in the Example project.

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add sticky_float_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  sticky_float_button: ^0.1.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:sticky_float_button/sticky_float_button.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:sticky_float_button/sticky_float_button.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Sticky Float Button',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const StickyFloatExample(),
    );
  }
}

class StickyFloatExample extends StatefulWidget {
  const StickyFloatExample({Key? key}) : super(key: key);

  @override
  _StickyFloatExampleState createState() => _StickyFloatExampleState();
}

class _StickyFloatExampleState extends State<StickyFloatExample> {
  AppBar _appBar() {
    return AppBar(
      title: const Text("Sticky Float Example"),
    );
  }

  Widget _body() {
    return Center(
      child: GestureDetector(onTap: () {}, child: const Text("Sticky")),
    );
  }

  Widget _floatButton() {
    return const CircleAvatar(
      backgroundColor: Colors.grey,
      child: Icon(
        Icons.add,
        color: Colors.white,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _appBar(),
      body: StickyBuilder(
        stickyButton: _floatButton(),
        child: _body(),
      ),
    );
  }
}

Author: Yoehwan
Source Code: https://github.com/yoehwan/flutter_sticky_float_button 
License: MIT license

#flutter #dart #button 

Sticky_float_button: A Flutter Implementation Of Sticky Float Button
Lawson  Wehner

Lawson Wehner

1658764200

Flutter-animated-Button: This is Animated Button for Flutter

animated_button_flutter

This is Flutter Animated Button.

Installation

dependencies:
  ...
  animated_button_flutter: ^0.0.5

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add animated_button_flutter

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  animated_button_flutter: ^0.0.5

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:animated_button_flutter/animated_button_flutter.dart';

example/lib/main.dart

import 'package:animated_button_flutter/animated_button.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Flutter Animated Button'),
        ),
        body: Center(
            child: Container(
                height: 40,
                width: double.maxFinite,
                margin: EdgeInsets.all(10),
                child: AnimatedButton(
                    text: "Animation Button",
                    backgroundColor: Colors.blue,
                    onTap: () {},
                    iconData: Icons.add,
                    radius: 20.0))));
  }
}

Author: gbhargavv
Source Code: https://github.com/gbhargavv/Flutter-Animated-Button 
License: View license

#flutter #animation #button #dart 

Flutter-animated-Button: This is Animated Button for Flutter
Hunter  Krajcik

Hunter Krajcik

1658518080

YG_indicator_button: Flutter UI Activity indicator Button

Features

image

Getting started

add yg_indicator_button: to your pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  yg_indicator_button:

Usage

TODO: Include short and useful examples for package users. Add longer examples to /example folder.

YGIndicatorButton(
    normalTitle: 'Create',
    height: 50,
    width: 200,
    action: (closure) {
        closure(YGIndicatorStatus.loading);
        // fake API request
    Future.delayed(const Duration(seconds: 2), () {
        closure(YGIndicatorStatus.completed);
    });
    },
)

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add yg_indicator_button

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  yg_indicator_button: ^0.0.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:yg_indicator_button/yg_indicator_button.dart';

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:yg_indicator_button/yg_indicator_button.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        child: YGIndicatorButton(
          normalTitle: 'Create',
          height: 50,
          width: 200,
          action: (closure) {
            closure(YGIndicatorStatus.loading);
            // fake API request
            Future.delayed(const Duration(seconds: 2), () {
              closure(YGIndicatorStatus.completed);
            });
          },
        ),
      ),
    );
  }
}

Author: hhgz9527
Source Code: https://github.com/hhgz9527/yg_indicator_button 
License: MIT license

#flutter #dart #button 

YG_indicator_button: Flutter UI Activity indicator Button