How To Get Each Character Entered In Text Field In Flutter App

admin_img Posted By Bajarangi soft , Posted On 07-11-2020

The TextField widget of flutter has a property named as onChanged() which calls every time when user types something in TextField widget. The onChanged() method returns us the typed character length in integer format. It will also count the empty space as single character.

How To Get Each Character Entered In Text Field In Flutter App

Get Each Char Entered In TextField
Complete Code For Get Each Char Entered In TextField In Flutter
main.dart

import 'package:flutter/material.dart';

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _textFieldController = TextEditingController();
  String _charEntered = '';

  _onChanged(String value) {
    setState(() {
      _charEntered = value.split("").last;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.deepPurple,
        title: Text('Get Each Char Entered In TextField'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Char Entered: " + _charEntered,
                style: TextStyle(fontSize: 18.0)),
            SizedBox(height: 20.0),
            Padding(
              //Add padding around textfield
              padding: EdgeInsets.symmetric(horizontal: 25.0),
              child: TextField(
                controller: _textFieldController,
                onChanged: _onChanged,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Related Post