0
votes

I have a database and retrieving my Data from firestore.

class ProductProvider with ChangeNotifier {
  UserModel userModel;
  List<UserModel> userModelList = [];
  Future<void> getUserData() async {
    List<UserModel> newList = [];
    User currentUser = FirebaseAuth.instance.currentUser;
    QuerySnapshot userSnapshot = await FirebaseFirestore.instance
        .collection("Manufacturer-Accounts")
        .get();

    userSnapshot.docs.forEach(
      (element) {
        if (currentUser.uid == element.data()['Manufacturer_ID']) {
          userModel = UserModel(
            userFName: element.data()['FirstName'],
            userCompany: element.data()['Company'],
            userDesignation: element.data()['Designation'],
            userEmail: element.data()['Email'],
            userPhone: element.data()['PhoneNumber'],
            userLastName: element.data()['LastName'],
          );
          newList.add(userModel);
        }
        userModelList = newList;
      },
    );
  }

I have retrieved my data as a list and set it to the textformfield like this in a stateful widget as I know the TextEditing Controller should be initiated in stateful widget and should not be as final.

class ProfileScreen extends StatefulWidget {
  static String routeName = "/Settings";

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

class _ProfileScreenState extends State<ProfileScreen> {
  var _formKey = GlobalKey<FormState>();
  File _pickedImageFile;
  PickedFile _pickedImage;
  TextEditingController firstName;
  TextEditingController lastName;
  TextEditingController phoneNumber;
  TextEditingController designation;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  User user = FirebaseAuth.instance.currentUser;

  void userDetailsUpdate() {
    FirebaseFirestore.instance
        .collection("Manufacturer-Accounts")
        .doc(user.uid)
        .update({
      'Designation': designation.text,
      'FirstName': firstName.text,
      'LastName': lastName.text,
      //'Email': user.email,
      'Phone': phoneNumber.text,
      //'UserImage': imageUrl == null ? "" : imageUrl,
    });
  }

  Future<void> getImage({ImageSource source}) async {
    _pickedImage = await ImagePicker().getImage(source: source);
    if (_pickedImage != null) {
      _pickedImageFile = File(_pickedImage.path);
    }
  }

  String imageUrl;
  void _uploadImage({File image}) async {
    StorageReference storageReference = FirebaseStorage.instance
        .ref()
        .child('UserImage')
        .child("UserImage/${user.uid}");
    StorageUploadTask uploadTask = storageReference.putFile(image);
    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    imageUrl = await taskSnapshot.ref.getDownloadURL();
  }

  Future<void> myDiscardChanges() {
    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          content: SingleChildScrollView(
            child: ListBody(
              children: [
                Text("Discard changes?"),
                SizedBox(height: 12),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    FlatButton(
                      padding: EdgeInsets.all(12),
                      color: Colors.amber[400],
                      hoverColor: Colors.blueGrey[300],
                      child: Text("Yes"),
                      onPressed: () {
                        setState(() {
                          editProfile = false;
                        });
                        Navigator.of(context).pop();
                      },
                    ),
                    FlatButton(
                      padding: EdgeInsets.all(12),
                      color: Colors.amber[400],
                      hoverColor: Colors.blueGrey[300],
                      child: Text("No"),
                      onPressed: () {
                        setState(() {
                          editProfile = true;
                        });
                        Navigator.of(context).pop();
                      },
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }

  Future<void> myDialogBox() {
    return showDialog<void>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            content: SingleChildScrollView(
              child: ListBody(
                children: [
                  ListTile(
                    leading: Icon(Icons.camera_alt),
                    title: Text("Camera"),
                    onTap: () {
                      getImage(source: ImageSource.camera);
                      Navigator.of(context).pop();
                    },
                  ),
                  ListTile(
                    leading: Icon(Icons.photo_library),
                    title: Text("Gallery"),
                    onTap: () {
                      getImage(source: ImageSource.gallery);
                      Navigator.of(context).pop();
                    },
                  )
                ],
              ),
            ),
          );
        });
  }

  bool editProfile = false;
  ProductProvider productProvider;
  Widget newBuildTrue() {
    List<UserModel> userModel = productProvider.getUserModelList;
    return Column(
      children: userModel.map((e) {
        //userImage = e.userImage;
        return Container(
          child: Column(
            children: [
              buildContainerTrue(
                startText: "First Name",
                endText: e.userFName,
              ),
              buildContainerTrue(
                startText: "Last Name",
                endText: e.userLastName,
              ),
              buildContainerTrue(
                startText: "E-mail",
                endText: e.userEmail,
              ),
              buildContainerTrue(
                startText: "Designation",
                endText: e.userDesignation,
              ),
              buildContainerTrue(
                startText: "Company",
                endText: e.userCompany,
              ),
              buildContainerTrue(
                startText: "Telephone No",
                endText: (e.userPhone).toString(),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  String userImage;
  Widget newBuildFalse() {
    List<UserModel> userModel = productProvider.getUserModelList;
    return Column(
      children: userModel.map((e) {
        //userImage = e.userImage;
        firstName = TextEditingController(text: e.userFName);
        lastName = TextEditingController(text: e.userLastName);
        phoneNumber = TextEditingController(text: e.userPhone);
        designation = TextEditingController(text: e.userDesignation);
        return Container(
          child: Column(
            children: [
              // buildTextFormField(editText: "FirstName"),
              MyTextFormField(
                name: "FirstName",
                controller: firstName,
              ),
              MyTextFormField(
                name: "LastName",
                controller: lastName,
              ),

              buildContainerTrue(
                startText: "E-mail",
                endText: e.userEmail,
              ),
              MyTextFormField(
                name: "Designation",
                controller: designation,
              ),
              buildContainerTrue(
                startText: "Company",
                endText: e.userCompany,
              ),
              MyTextFormField(
                name: "Telephone No",
                controller: phoneNumber,
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

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

  @override
  void dispose() {
    //firstName.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    productProvider = Provider.of<ProductProvider>(context);
    productProvider.getUserData();
    ScreenUtil.init(context, height: 896, width: 414, allowFontScaling: true);
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        leading: editProfile == false
            ? IconButton(
                icon: Icon(Icons.menu),
                color: kPrimaryColor,
                onPressed: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (BuildContext context) => MenuFrame(),
                    ),
                  );
                },
              )
            : Container(),
        elevation: 1,
        actions: [
          editProfile == false
              ? IconButton(
                  icon: Icon(Icons.edit),
                  color: kPrimaryColor,
                  onPressed: () {
                    setState(() {
                      editProfile = true;
                    });
                  },
                )
              : IconButton(
                  icon: Icon(Icons.close),
                  color: kPrimaryColor,
                  onPressed: () {
                    myDiscardChanges();
                  },
                ),
        ],
      ),
      body: Form(
        key: _formKey,
        child: Container(
          height: double.infinity,
          width: double.infinity,
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Container(
                    height: kSpacingUnit.w * 10,
                    width: kSpacingUnit.w * 10,
                    margin: EdgeInsets.only(top: kSpacingUnit.w * 3),
                    child: Stack(
                      children: <Widget>[
                        CircleAvatar(
                          radius: kSpacingUnit.w * 8,
                          backgroundImage: _pickedImageFile == null
                              ? AssetImage('assets/images/12.jpg')
                              : FileImage(_pickedImageFile),
                        ),
                        editProfile == true
                            ? Align(
                                alignment: Alignment.bottomRight,
                                child: Container(
                                  height: kSpacingUnit.w * 2.5,
                                  width: kSpacingUnit.w * 2.5,
                                  decoration: BoxDecoration(
                                    color: kAccentColor,
                                    shape: BoxShape.circle,
                                  ),
                                  child: Center(
                                    heightFactor: kSpacingUnit.w * 1.5,
                                    widthFactor: kSpacingUnit.w * 1.5,
                                    child: GestureDetector(
                                      onTap: () {
                                        myDialogBox();
                                      },
                                      child: Icon(
                                        LineAwesomeIcons.pen,
                                        color: kDarkPrimaryColor,
                                        size: ScreenUtil()
                                            .setSp(kSpacingUnit.w * 1.5),
                                      ),
                                    ),
                                  ),
                                ),
                              )
                            : Container(),
                      ],
                    )),
                SizedBox(height: kSpacingUnit.w * 1.5),
                editProfile == false ? newBuildTrue() : newBuildFalse(),
                editProfile == true
                    ? FlatButton(
                        color: Colors.amber,
                        height: 50,
                        minWidth: 400,
                        child: Text("Save"),
                        onPressed: () {
                          userDetailsUpdate();
                          //_uploadImage(image: _pickedImageFile);
                          setState(() {
                            editProfile = false;
                          });
                        },
                      )
                    : Container(),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget buildContainerTrue({String startText, String endText}) {
    return Container(
      height: kSpacingUnit.w * 5.5,
      margin: EdgeInsets.symmetric(
        horizontal: kSpacingUnit.w * 2,
      ).copyWith(
        bottom: kSpacingUnit.w * 2,
      ),
      padding: EdgeInsets.symmetric(
        horizontal: kSpacingUnit.w * 1.5,
      ),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(kSpacingUnit.w * 3),
        color: kDarkSecondaryColor,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            alignment: Alignment.centerLeft,
            width: 100,
            height: kSpacingUnit.w * 5.5,
            decoration: BoxDecoration(
              // color: Colors.green,
              border: Border(
                right: BorderSide(color: Colors.white, width: 1),
              ),
            ),
            child: Text(
              startText,
              style: TextStyle(color: Colors.white, fontSize: 12),
              textAlign: TextAlign.left,
            ),
          ),
          SizedBox(width: kSpacingUnit.w * 1.5),
          Text(
            endText,
            style: kTitleTextStyle.copyWith(
              fontWeight: FontWeight.w500,
              color: Colors.amber,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

But still following the procedures I am facing an issue like when I enter my new value to the controller it still shows a new value when my keyboard exit. Tried lot of ways and still having the same issue.

1
I did not understand your explanation of the problem. (last paragraph)Claudio Castro
If your problem is that the value of your textfield is returning to its original value, note that in the construction of your table, your textfield controllers gain their original value again. So the original value will always be loaded when you hear an update to the table widget.Claudio Castro
I need to insert a new value to my controller as an initial value it should show the values from firestore collection when I enter a new value it should show the new entered text. But in my situation when I try to close my keyboard it automatically returns to the value which was initiatedJude Harshan
Yes thats the issue which i am currently facing what is the suitable way of doing it then?Jude Harshan
Just with the code shown, I can't give you an answer. The idea is that newBuildFalse () is called only when you load the data. Something is causing him to be called more often.Claudio Castro

1 Answers

0
votes

Making changes to my functions it actually worked.

Widget newBuildTrue() {
    List<UserModel> userModel = productProvider.getUserModelList;
    return Column(
      children: userModel.map((e) {
        firstName = TextEditingController(text: e.userFName);
        lastName = TextEditingController(text: e.userLastName);
        phoneNumber = TextEditingController(text: e.userPhone);
        designation = TextEditingController(text: e.userDesignation);
        //userImage = e.userImage;
        return Container(
          child: Column(
            children: [
              buildContainerTrue(
                startText: "First Name",
                endText: e.userFName,
              ),
              buildContainerTrue(
                startText: "Last Name",
                endText: e.userLastName,
              ),
              buildContainerTrue(
                startText: "E-mail",
                endText: e.userEmail,
              ),
              buildContainerTrue(
                startText: "Designation",
                endText: e.userDesignation,
              ),
              buildContainerTrue(
                startText: "Company",
                endText: e.userCompany,
              ),
              buildContainerTrue(
                startText: "Telephone No",
                endText: (e.userPhone).toString(),
              ),
            ],
          ),
        );
      }).toList(),
    );
  }

  String userImage;
  Widget newBuildFalse() {
    List<UserModel> userModel = productProvider.getUserModelList;
    return Column(
      children: userModel.map((e) {
        //userImage = e.userImage;

        return Container(
          child: Column(
            children: [
              // buildTextFormField(editText: "FirstName"),
              MyTextFormField(
                name: "FirstName",
                controller: firstName,
              ),
              buildTextFormField(
                editText: "LastName",
                textEditingController: lastName,
              ),

              buildContainerTrue(
                startText: "E-mail",
                endText: e.userEmail,
              ),
              MyTextFormField(
                name: "Designation",
                controller: designation,
              ),
              buildContainerTrue(
                startText: "Company",
                endText: e.userCompany,
              ),
              MyTextFormField(
                name: "Telephone No",
                controller: phoneNumber,
              ),
            ],
          ),
        );
      }).toList(),
    );
  }