乐闻世界logo
搜索文章和话题

How do I supply an initial value to a text field in Flutter?

1个答案

1

In Flutter, setting initial values for text fields typically involves using TextEditingController. This controller not only manages the text within the text field but also sets the initial value. Below, I'll demonstrate how to set an initial value for a text field with a simple example.

First, create a TextEditingController in Flutter and pass the initial value via its constructor:

dart
TextEditingController _controller = TextEditingController(text: "Initial Value");

Next, bind this controller to a TextField component:

dart
TextField( controller: _controller, )

The complete example might look like this:

dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { TextEditingController _controller; void initState() { super.initState(); // Set the initial value for the text field here _controller = TextEditingController(text: "Initial Value"); } void dispose() { // Ensure to release resources when the widget is disposed _controller.dispose(); super.dispose(); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter Demo'), ), body: Center( child: TextField( controller: _controller, ), ), ); } }

In this example, we first create a TextEditingController and set an initial value via the text parameter: "Initial Value". This controller is then bound to the TextField component, so when the app runs and displays this TextField, it pre-fills with the initial value.

This approach is very useful, especially when handling forms and input fields, where you might need to pre-populate existing data for users to view and modify as needed.

2024年7月1日 12:49 回复

你的答案