首页 > 解决方案 > 如何将未来的字符串设置为 TextFormField 的“初始值”

问题描述

大家好我是初学者。我面临一个问题。下面是我的代码。我想将 Future String 设置为 TextFormField 的初始值。我只为一个 TextFormField 成功完成了此操作,但现在我有多个 TextFormField,我尝试从 firebase 文档的每个字段中获取数据并将其设置为相应 TextFormField 的初始值。

如果我将值分配给 TextFormField“标签”,它会正确显示,但是当我将相同的值分配给“初始值”时,它不会显示。抱歉谈话不佳

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:shop_app/components/custom_surfix_icon.dart';
import 'package:shop_app/components/default_button.dart';
import 'package:shop_app/components/form_error.dart';
import 'package:shop_app/size_config.dart';

import '../../../../../../constants.dart';

class EditProfileForm extends StatefulWidget {
  @override
  _EditProfileFormState createState() => _EditProfileFormState();
}

class _EditProfileFormState extends State<EditProfileForm> {
  final _formKey = GlobalKey<FormState>();
  final List<String> errors = [];

  String name;
  String phoneNo;
  String gender;
  String address;
  String about;
  String education;
  String specialities;
  String languages;
  String work;

  String storeName;
  String storePhoneNo;
  String storeGender;
  String storeAddress;
  String storeAbout;
  String storeEducation;
  String storeSpecialities;
  String storeLanguages;
  String storeWork;

  static const menuItems = <String>[
    'Male',
    'Female',
    'Other',
  ];
  final List<DropdownMenuItem<String>> popUpMenuItem = menuItems
      .map((String value) => DropdownMenuItem<String>(
            value: value,
            child: Text(value),
          ))
      .toList();

  void addError({String error}) {
    if (!errors.contains(error))
      setState(() {
        errors.add(error);
      });
  }

  void removeError({String error}) {
    if (errors.contains(error))
      setState(() {
        errors.remove(error);
      });
  }

//   @override
//     void initState() {
//     super.initState();
//     getData();
    
// }

  getData() {
    getName();
    getPhoneNo();
    getAddress();
    getAbout();
    getEducation();
    getSpecialities();
    getLanguages();
    getWork();
  }

  @override
  Widget build(BuildContext context) {
    return Form(
          key: _formKey,
          child: Column(
            children: [
              getNameFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getGenderFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getPhoneNoFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getAddressFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getAboutFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getEducationFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getSpecialitiesFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getLanguagesFormField(),
              SizedBox(height: getProportionateScreenHeight(30)),
              getWorkFormField(),
              FormError(errors: errors),
              SizedBox(height: getProportionateScreenHeight(40)),
              DefaultButton(
                text: "Update Profile",
                press: () async {
                  if (_formKey.currentState.validate()) {
                    print(storeName);
                  }
                },
              ),
            ],
          ),
        );
  }


  ///////////////////////////////////////////////////////////////////////////////
  Widget getNameFormField() {
    return FutureBuilder(
      future: getName(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        storeName = snapshot.data;
        return TextFormField(
          initialValue: storeName,
          onSaved: (newValue) => name = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kNamelNullError);
            }
            name = value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kNamelNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: storeName,
            hintText: "Enter your name",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
          ),
        );
      },
    );
  }

  Future<String> getName() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getName = document['Name'];
    return getName;
  }

  ///////////////////////////////////////////////////////////////////////////////

  Widget getPhoneNoFormField() {
    return FutureBuilder(
      future: getPhoneNo(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot1) {
        storePhoneNo = snapshot1.data;
        return TextFormField(
          initialValue: storePhoneNo,
          onSaved: (newValue) => phoneNo = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kPhoneNumberNullError);
            }
            phoneNo = value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kPhoneNumberNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: "Phone No",
            hintText: "Enter Phone No",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Phone.svg"),
          ),
        );
      },
    );
  }
  
  Future<String> getPhoneNo() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getPhoneNo = document['Phone Number'];
    return getPhoneNo;
  }

  ///////////////////////////////////////////////////////////////////////////////

  DropdownButtonFormField getGenderFormField() {
    return DropdownButtonFormField(
      onSaved: (newValue) {
        gender = newValue;
      },
      onChanged: (value) {
        if (value.isNotEmpty) {
          removeError(error: kNamelNullError);
        }
        gender = value;
        print(gender);
      },
      validator: (value) {
        if (value.isEmpty) {
          addError(error: kNamelNullError);
          return "";
        }
        return null;
      },
      decoration: InputDecoration(
        labelText: "Gender",
        hintText: "Select your gender",
        floatingLabelBehavior: FloatingLabelBehavior.always,
        suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/gender.svg"),
      ),
      items: popUpMenuItem,
    );
  }

  Future<String> getGender() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getGender = document['Gender'];
    return getGender;
  }

  ///////////////////////////////////////////////////////////////////////////////

  Widget getAddressFormField() {
    return FutureBuilder(
      future: getAddress(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot2) {
        storeAddress = snapshot2.data;
        return TextFormField(
          initialValue: storeAddress,
          onSaved: (newValue) => address = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kAddressNullError);
            }
            address = value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kAddressNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: "Address",
            hintText: "Enter your address",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/Location point.svg"),
          ),
        );
      },
    );
  }
  
  Future<String> getAddress() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getName = document['Address'];
    return getName;
  }

  ///////////////////////////////////////////////////////////////////////////////

  Widget getAboutFormField() {
    return FutureBuilder(
      future: getAbout(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot3) {
        storeAbout = snapshot3.data;
        return TextFormField(
          initialValue: storeAbout,
          onSaved: (newValue) => about = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kAboutNullError);
            }
            about = value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kAboutNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: "About",
            hintText: "Describe Yourself",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
          ),
        );
      },
    );
  }

  Future<String> getAbout() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getAbout = document['About'];
    return getAbout;
  }

  ///////////////////////////////////////////////////////////////////////////////

  Widget getEducationFormField() {
    return FutureBuilder(
      future: getEducation(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot4) {
        storeEducation = snapshot4.data;
        return TextFormField(
          initialValue: storeEducation,
          onSaved: (newValue) => education = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kEducationNullError);
            }
            education = value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kEducationNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: "Education",
            hintText: "Enter your education",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
          ),
        );
      },
    );
  }

  Future<String> getEducation() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getEducation = document['Education'];
    return getEducation;
  }

  ///////////////////////////////////////////////////////////////////////////////

  Widget getSpecialitiesFormField() {
    return FutureBuilder(
      future: getSpecialities(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot5) {
        storeSpecialities = snapshot5.data;
        return TextFormField(
          initialValue: storeSpecialities,
          onSaved: (newValue) => specialities = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kSkillsNullError);
            }
            specialities = value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kSkillsNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: "Specialities",
            hintText: "Enter your specialities",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
          ),
        );
      },
    );
  }

  Future<String> getSpecialities() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getSpecialities = document['Specialities'];
    return getSpecialities;
  }

  ///////////////////////////////////////////////////////////////////////////////

  Widget getLanguagesFormField() {
    return FutureBuilder(
      future: getLanguages(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot6) {
        storeLanguages = snapshot6.data;
        return TextFormField(
          initialValue: storeLanguages,
          onSaved: (newValue) => languages = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kLanguagesNullError);
            }
            languages = value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kLanguagesNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: "Languages",
            hintText: "Enter Your Languages",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
          ),
        );
      },
    );
  }

  Future<String> getLanguages() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getLanguages = document['Languages'];
    return getLanguages;
  }

  ///////////////////////////////////////////////////////////////////////////////

  Widget getWorkFormField() {
    return FutureBuilder(
      future: getWork(),
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot7) {
        storeWork = snapshot7.data;
        return TextFormField(
          initialValue: storeWork,
          onSaved: (newValue) => work = newValue,
          onChanged: (value) {
            if (value.isNotEmpty) {
              removeError(error: kWorkNullError);
            }
            work= value;
          },
          validator: (value) {
            if (value.isEmpty) {
              addError(error: kWorkNullError);
              return "";
            }
            return null;
          },
          decoration: InputDecoration(
            labelText: "Work",
            hintText: "What you do?",
            floatingLabelBehavior: FloatingLabelBehavior.always,
            suffixIcon: CustomSurffixIcon(svgIcon: "assets/icons/User.svg"),
          ),
        );
      },
    );
  }

  Future<String> getWork() async {
    DocumentSnapshot document = await FirebaseFirestore.instance
        .collection('Users')
        .doc(FirebaseAuth.instance.currentUser.email)
        .get();
    String getWork = document['Work'];
    return getWork;
  }


}

标签: stringfirebaseflutterdartgoogle-cloud-firestore

解决方案


您可以在 initState() 中调用返回 Future 字符串的函数,之后,您可以将该字符串设置为 TextInput 提示


推荐阅读