Home > database >  Refactoring of TextField/TextFormField in Flutter
Refactoring of TextField/TextFormField in Flutter

Time:03-15

Can we refactor TextField/TextFormField in Flutter without rebuilding the Widget? I tried to refactor TextField Widget for a form that I have created to collect some data. But, when I dismiss my keyboard the data is losing because the widget is rebuilding. Is there any way to fix it? Pls Let me know...

See the code below of the Refactored TextField

import 'package:flutter/material.dart';

class ContentInputWidget extends StatelessWidget {
  const ContentInputWidget({
    Key? key,
    required this.text,
    required this.controller,
    this.keyboardType = TextInputType.text,
  }) : super(key: key);

  final String text;
  final TextInputType keyboardType;
  final TextEditingController controller;

  @override
  Widget build(BuildContext context) {
    print('Content Input Widget Rebuild');
    return TextField(
      decoration: InputDecoration(
        labelText: text,
        border: const OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(15),
          ),
        ),
      ),
      controller: controller,
      keyboardType: keyboardType,
      maxLines: null,
    );
  }
}

CodePudding user response:

You can set up your TextFieldController using flutter_hooks (useTextEditingController). This will make it so the state of the TextEditingController isn't lost on rebuilds.

TextEditingController controller = useTextEditingController();

CodePudding user response:

I had a similar problem a long time ago. I don't remember exactly how I made it work, but you could try adding a onChanged function to your TextField and save the data before the re-build clears the text.

final String myText; 

void _onChanged() {
  if (controller.text != null && controller.text != "") {
    myText = controller.text;
  }
}

  @override
  Widget build(BuildContext context) {
    print('Content Input Widget Rebuild');
    return TextField(
      onChanged: _onChanged,
      decoration: InputDecoration(
        labelText: text,
        border: const OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(15),
          ),
        ),
      ),
      controller: controller,
      keyboardType: keyboardType,
      maxLines: null,
    );
  }
  • Related