Home > database >  Flutter: How can I set initial value to a textController and change it after?
Flutter: How can I set initial value to a textController and change it after?

Time:02-12

I have a stepper and some TextFormFields with controller in the first step. I want to show in the TextField an initialValue and if I change the value want to set the new value to the controller and keep it on change step. Now, I can change the value of the controller but not keep it on change step

Edit Page

class EditProfilePage extends StatefulWidget {
  final String uid;

  const EditProfilePage({Key? key, required this.uid}) : super(key: key);

  @override
  _EditProfilePageState createState() => _EditProfilePageState();
}

class _EditProfilePageState extends State<EditProfilePage> {
  final TextEditingController _nameController = TextEditingController();

 int _index = 0;

  @override
  void initState() {
    super.initState();
    _nameController.addListener(() {
      final String text = _nameController.text;
      _nameController.value = _nameController.value.copyWith(
        text: text,
      );
    });
  }

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

  @override
  Widget build(BuildContext context) {
;
final UserProvider userProvider = Provider.of<UserProvider>(context);

_nameController.text = userProvider.getUser.name;
return Scaffold(
    ...
    body: Stepper(
        controlsBuilder: (BuildContext context, ControlsDetails details) {
          if (_index == 2) {
            return Container(
              padding: const EdgeInsets.only(right: 20),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () {
                      userProvider.updateName(
                          _nameController.text, userProvider.getUser.uid);
                    },
                    child: const Text('SAVE'),
                  ),
                ],
              ),
            );
          } else {
            return Row();
          }
        },
        currentStep: _index,
        onStepCancel: () {
          _index > 0 ? setState(() => _index -= 1) : null;
        },
        onStepContinue: () {
          _index < 2 ? setState(() => _index  = 1) : null;
        },
        onStepTapped: (int index) {
          setState(() {
            _index = index;
          });
        },
        steps: <Step>[
          Step(
            title: const Text('Personal Info'),
            content: Container(
                padding: const EdgeInsets.all(5),
                child: Column(children: [
                  TextFormField(
                    controller: _nameController,
                    decoration: InputDecoration(
                      labelText: 'Name',
                      labelStyle: const TextStyle(color: Colors.black54),
                      border: const OutlineInputBorder(),
                      focusedBorder: OutlineInputBorder(
                        borderSide: Divider.createBorderSide(context),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: Divider.createBorderSide(context),
                      ),
                      filled: true,
                      contentPadding: const EdgeInsets.all(8),
                    ),
                  ),
                  const SizedBox(
                    height: 24,
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

UserProvider

class UserProvider with ChangeNotifier {
  User? _user;
  final AuthMethods _authMethods = AuthMethods();

  User get getUser => _user!;

  Future<void> refreshUser() async {
    User user = await _authMethods.getUserDetails();
    _user = user;
    notifyListeners();
  }

  Future<void> deleteFriends(int index, String uid) async {
    try {
      final userSnap =
          await FirebaseFirestore.instance.collection('users').doc(uid).get();
      final list = userSnap["friends"] as List;
      list.removeAt(index);
      await FirebaseFirestore.instance
          .collection('users')
          .doc(uid)
          .update({"friends": list}).then((value) => print(" Deleted"));
      refreshUser();
    } catch (err) {
      print(err.toString());
    }
  }
...

CodePudding user response:

You can use

TextEditingController.fromValue(TextEditingValue(text: "initial value"));

or

TextEditingController(text: "initial value")

More about TextEditingController.

CodePudding user response:

To set the initial value to a TextEditingController

 final _nameController = TextEditingController(text: 'initial value');

And to update the value:

 _nameController.text='new value';
  • Related