Home > Enterprise >  how to input a string to textfield
how to input a string to textfield

Time:02-18

Is it possible that the last String from a list can be input automatically to a TextField?

The list is empty for first few seconds and it is changing. It is also initialize after build context.

If yes please provide a code because I am new to flutter.

I know how to change the text from a textfield by using TextEditingController.

final TextEditingController _controller = TextEditingController();

TextField(controller: _controller)

ElevatedButton(
  onPressed: () {
    const newText = 'Hello World';
    final updatedText = _controller.text   newText;
    _controller.value = _controller.value.copyWith(
      text: updatedText,
      selection: TextSelection.collapsed(offset: updatedText.length),
    );
  },
)

but it has a button, how can I automate this?

CodePudding user response:

Yes you can do this by TextEditingController... Let's have a code example where you have a List of String.... e.g


import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late TextEditingController _textEditingController;
  final List<String> _exampleList = [];

  @override
  void initState() {
    Future.delayed(
      const Duration(seconds: 2),
      () {
        if (mounted) {
          setState(() {
            _exampleList.add("apple");
            _textEditingController = TextEditingController(text: _exampleList.last);
          });
        }
      },
    );

    _textEditingController = TextEditingController(text: "Loading ...");

    super.initState();
  }

  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: TextFormField(
            enabled: _exampleList.isNotEmpty,
            controller: _textEditingController,
          ),
        ),
      ),
    );
  }
}



here is the result... this is just a simple explanation of how you can show last item of list in textfield

enter image description here

  • Related