Flutter - How do texts swap TextFields?

Viewed 89

I need to create some void Function() that is called when FloatingActionButton is tapped. How to make texts swap TextFields, so that first text goes in second TextField and second text goes in first TextField. I don't know how to make things happen, but I know it has something to do with the key.

//... 

class _TextsSwapTextFieldsState extends State<TextsSwapTextFields> {
  final firstController = TextEditingController();
  final secondController = TextEditingController();

  @override
  void dispose() {
    firstController.dispose();
    secondController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // doesn't work
          // firstController.text = secondController.text;
          // secondController.text = firstController.text;
        },
        child: const Icon(Icons.text_fields),
      ),
      appBar: AppBar(
        backgroundColor: const Color(0xFFFAFAFA),
        elevation: 0.0,
        centerTitle: true,
        title: 'Texts Swap TextFields',
      ),
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(
              flex: 5,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16.0),
                child: Column(
                  children: [
                    TextFormField(
                      controller: firstController,
                      style: textFieldStyle,
                      onChanged: (text) {
                        print('First text field: $text');
                      },
                      decoration: kTextFieldDecoration.copyWith(
                        hintText: 'from',
                      ),
                    ),
                    const SizedBox(
                      height: 8.0,
                    ),
                    TextFormField(
                      controller: secondController,
                      style: textFieldStyle,
                      onChanged: (text) {
                        print('Second text field: $text');
                      },
                      decoration: kTextFieldDecoration.copyWith(
                        hintText: 'to',
                      ),
                    ),
                  ],
                ),
              ),
            ),
            //... 
1 Answers

Put this function in your code and call on button click

void swapValues(){
      var temp = firstController.text.toString();
      setState(){
        firstController.text = secondController.text.toString();
        secondController.text = temp;
      }
    }
Related