Clear Number Input In Flutter

Clear Number Input In Flutter :

ClearableNumberInput property :

  • onChange: (value): Change the value display in TextField.
  • value: Starting text display. That value is pass TextEditingController.
  • hintText: TextField hint.
  • style: TextField text style apply.
  • contentPadding: Padding inside the InputDecoration.
  • border: Default border none.

_ClearableNumberInputState(value)
: _controller = value == null
? TextEditingController()
: TextEditingController.fromValue(
TextEditingValue(text: value.toString())
);

That value is store _controller. if value is null then TextEditingController() else TextEditingController.fromValue( TextEditingValue(text: value.toString()));

Screenshot 1 :

Clear Number Input In Flutter

Screenshot 2 :

Clear Number Input In Flutter

input_formatter.dart

import 'package:flutter/services.dart';

class DecimalInputFormatter implements TextInputFormatter {
  TextEditingValue formatEditUpdate(
      TextEditingValue old, TextEditingValue next) {
    final validNew = isValid(next.text);
    if (validNew) {
      return next;
    } else {
      return old;
    }
  }

  // TODO: probably better handled by regex
  bool isValid(String value) {
    if (value == '') {
      return true;
    }
    if (double.tryParse(value) == null) {
      return false;
    }
    if (value.startsWith('00')) {
      return false;
    }
    if (value.contains(' ')) {
      return false;
    }
    if (value.length > 1 && value.startsWith('0') && value[1] != '.') {
      return false;
    }
    var sides = value.split('.');
    if (sides.length > 1 && sides[1].length > 2) {
      return false;
    }
    return true;
  }
}

number_input.dart

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:quiver/strings.dart';
import 'input_formatter.dart';

class ClearableNumberInput extends StatefulWidget {
  final Function(double) onChange;
  final double value;
  final String hintText;
  final TextStyle style;
  final EdgeInsetsGeometry contentPadding;
  final InputBorder border;

  ClearableNumberInput({
    @required this.onChange,
    @required this.value,
    @required this.hintText,
    this.style,
    this.contentPadding,
    this.border,
  });

  @override
  State<StatefulWidget> createState() => _ClearableNumberInputState(value);
}

class _ClearableNumberInputState extends State<ClearableNumberInput> {
  final _focus = FocusNode();
  final _controller;

  bool focused = false;

  _ClearableNumberInputState(value)
      : _controller = value == null
            ? TextEditingController()
            : TextEditingController.fromValue(
                TextEditingValue(text: value.toString()));

  @override
  void initState() {
    _focus.addListener(() => focused = !focused);
    super.initState();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  void handleChange(var number) {
    widget.onChange(isBlank(number) ? null : double.parse(number));
  }

  bool isClearable() {
    return !isBlank(_controller.text);
  }

  @override
  Widget build(BuildContext context) {
    print(_focus);
    return TextField(
      controller: _controller,
      keyboardType: TextInputType.numberWithOptions(decimal: true),
      inputFormatters: [DecimalInputFormatter()],
      style: widget.style,
      focusNode: _focus,
      onChanged: handleChange,
      decoration: InputDecoration(
        contentPadding: widget.contentPadding ?? EdgeInsets.all(16.0),
        hintText: widget.hintText,
        border: widget.border ?? InputBorder.none,
        isDense: true,
        suffixIcon: focused
            ? IconButton(
                icon: Icon(Icons.clear),
                disabledColor: Colors.transparent,
                onPressed: isClearable() ? () => _controller.clear() : null,
              )
            : null,
      ),
    );
  }
}

main.dart

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ClearNumberInputPage(title: 'Flutter Tutorial'),
    );
  }
}

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

  final String title;

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

class _ClearNumberInputState extends State<ClearNumberInputPage> {
  double _amount;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Center(
            child: ClearableNumberInput(
          onChange: (value) {
            setState(() {
              this._amount = value;
            });
          },
          value: _amount,
          hintText: "Enter price",
          style: Theme.of(context).textTheme.body1,
          contentPadding: EdgeInsets.all(16.0),
          border: InputBorder.none,
        )));
  }
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in