Flutter textfield double only

HTML Content: Flutter TextField

Flutter provides the TextField widget for capturing user input. It can be used to accept various types of input, including doubles.

     
import 'package:flutter/material.dart';

class MyTextField extends StatefulWidget {
  @override
  _MyTextFieldState createState() => _MyTextFieldState();
}

class _MyTextFieldState extends State {
  double inputValue = 0.0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextField Example'),
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(20.0),
          child: TextField(
            onChanged: (value) {
              setState(() {
                inputValue = double.tryParse(value) ?? 0.0;
              });
            },
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              labelText: 'Enter a double',
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // Do something with the double value
          print(inputValue);
        },
        child: Icon(Icons.check),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: MyTextField(),
  ));
}
     
   

In the above example, we create a TextField widget that accepts double values. Here are the important parts:

  • Create a StatefulWidget class to manage the state of the TextField.
  • Define a variable, `inputValue`, to store the entered double value.
  • In the `build` method, we create a Scaffold and place the TextField widget inside a Center widget for alignment.
  • We set the `onChanged` property of the TextField to update the `inputValue` whenever the user enters a new value. We use `double.tryParse` to convert the input string to a double, and if it fails, we assign a default value of 0.0.
  • We set the `keyboardType` property of the TextField to `TextInputType.number` to display a numeric keyboard.
  • We provide a `decoration` property to customize the appearance of the TextField.
  • We also add a FloatingActionButton which, when pressed, prints the `inputValue` to the console. You can replace this `onPressed` function with your desired logic.
  • In the `main` function, we wrap our `MyTextField` widget inside a MaterialApp and run the app.

With this example, when you run the app, you will see a screen with a TextField that accepts double values. As you type in the TextField, the `inputValue` variable will be updated accordingly, and you can perform any desired actions with that double value.

Leave a comment