Home > Mobile >  I am getting a range error in textfield when i remove all the elements form the textflield in my flu
I am getting a range error in textfield when i remove all the elements form the textflield in my flu

Time:01-25

I am facing an error when i use backspace to remove all the content in the textfield.The error that i am getting is this:

The following RangeError was thrown while handling a gesture: RangeError (end): Invalid value: Only valid value is 0: -1

and is there a way by which the "Rs." string remains in the textfield and it should not be deleted when i press the backspace button on the numpad.

import 'package:flutter/material.dart';
import 'package:sadapay_clone/screens/homepage.dart';
import 'package:sadapay_clone/widgets/numpad.dart';

class SendMoney extends StatefulWidget {
  const SendMoney({super.key});

  @override
  State<SendMoney> createState() => _SendMoneyState();
}

class _SendMoneyState extends State<SendMoney> {
  final TextEditingController _myController = TextEditingController();
  @override
  void initState() {
    super.initState();
    _myController.text = 'Rs. ';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 255, 129, 129),
      body: Column(
        children: [
          const SizedBox(height: 75),
          SizedBox(
            height: 70,
            child: Center(
              child: TextField(
                controller: _myController,
                textAlign: TextAlign.center,
                showCursor: false,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 40,
                ),
                keyboardType: TextInputType.none,
                decoration: const InputDecoration(border: InputBorder.none),
                enabled: false,
                
              ),
            ),
          ),
          NumPad(
            controller: _myController,
            delete: () {
              _myController.text = _myController.text
                  .substring(0, _myController.text.length - 1);
            },
            onSubmit: () {},
          ),

CodePudding user response:

The error comes because when the textFiled is empty it cant create subString from.

.substring(0, _myController.text.length - 1);

You can do a length check and then create a subString

delete: () {
  if(_myController.text.length>3){ // check if Rs needed any space, change the `3` based on your need
      _myController.text = _myController.text
        .substring(0, _myController.text.length - 1);
    }
  },
  • Related