Handling Text in Flutter

Flutter: TextField or TextFromField

To add a text, we can use TextField or TextFromField Widget:


Row(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 16),
child: TextFormField(
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your username',
),
),
),
),
],
)

To handle the user input we need to use TextEditController
First we need to declare this:

  final myController = TextEditingController();


Its good practice to dispose it when widget is offloaded, following code will dispose
controller:

  @override
  void dispose() {
    // Clean up the controller when the widget is removed from the
    // widget tree.
    myController.dispose();
    super.dispose();
  }

Now we can use this controller in TextField or TextFromField
TextField(
  controller: myController,
),

Following the above example:
Row(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 16),
child: TextFormField(
          controller: myController  
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your username',
),
),
),
),
],
)

Use following text property to make TextField as "password field"
obscureText: true,
For Example:
Row(children: [
Expanded(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
child: TextFormField(
controller: passwordController,
obscureText: true,
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your password',
),
),
),
),
]),

We can use onChanged function to read changes in TextField or TextFromField
onChanged: (value){print(value);},
For Example:
Row(
mainAxisSize: MainAxisSize.max,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 16),
child: TextFormField(
controller: usernameController,
decoration: const InputDecoration(
border: UnderlineInputBorder(),
labelText: 'Enter your username',
),
onChanged: (value){print(value);},
),
),
),
],
),

Comments

  1. Text handling in Flutter is fundamental for UI design. Understanding how to style, format, and display text is essential for creating visually appealing and user-friendly apps. If you are looking forward to Hire React Native Developers, we will gladly help you.

    ReplyDelete

Post a Comment