简体   繁体   中英

Update data in database Firestore through TextFormField - Flutter

How to make the data that is written in the TextFormField update the data that has already been recorded

here is my login screen. This is part of the registration page. the same code on the login page

String _email, _password, id;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final db = Firestore.instance;

Expanded(
                        child: TextFormField(
                          autofocus: false,
                          // controller: _email,
                          // validator: Validator.validateEmail,
                          onSaved: (input) => _email = input,
                          decoration: InputDecoration(
                            border: InputBorder.none,
                            hintText: 'Enter your email',
                            hintStyle: TextStyle(color: Colors.grey),
                          ),
                        ),
                      ),
Expanded(
                        child: FlatButton(
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(30.0),
                          ),
                          color: Colors.blue,
                          onPressed: () {},
                          child: Row(
                            children: <Widget>[
                              Padding(
                                padding: EdgeInsets.only(left: 20.0),
                                child: Text(
                                  'SIGN UP',
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                              Expanded(
                                child: Container(),
                              ),
                              Transform.translate(
                                offset: Offset(10.0, 0.0),
                                child: Container(
                                  padding: EdgeInsets.all(1.0),
                                  child: FlatButton(
                                    shape: RoundedRectangleBorder(
                                      borderRadius: 
                                       BorderRadius.circular(28.0)
                                    ),
                                    color: Colors.white,
                                    child: Icon(
                                      Icons.arrow_forward,
                                      color: Colors.blue,
                                    ),
                                    onPressed: () async {
                                      // _emailSignUp(
                                      //   email:_email.text,
                                      //   password:_password.text,
                                      //   context: context
                                      // );

                                      createData();
                                      signUp();
                                      sharedPreferences = await 
                     SharedPreferences.getInstance();

                     sharedPreferences.setString("email", _email);
                                    },
                                  ),
                                ),
                              )
                            ],
                          ),
                        ),
                      )
 void createData() async {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      DocumentReference ref = await db.collection('users').add({'email': '$_email', 'name': 'UserName', 'userPhotoURL': 'url'});
      setState(() => id = ref.documentID);
      print(ref.documentID);
    }
  }

AccountScreen. Here I want to update the data users through TextFormField. I want to determine what data needs to be changed depending on the user who came in

class AccountScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => AccountScreenState();
}

class AccountScreenState extends State<AccountScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String countries;
  String selected;
  SharedPreferences sharedPreferences;
  String _name, _email;
  final db = Firestore.instance;

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

  getDataPreference() async {
    sharedPreferences = await SharedPreferences.getInstance();
    setState(() {
      _email = sharedPreferences.getString("email");
    });
  }

  // void updateData(DocumentSnapshot doc) async {
  //   await db.collection('users').document(doc.documentID).updateData({'email': '$_email', 'name': '$_name'});
  //   Navigator.of(context).pushReplacementNamed('/home_screen');
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text("Your account"), backgroundColor: Colors.blueGrey[900]),
      body: 
      Container(
        color: Colors.blueGrey[800],
        child: Form(
          key:_formKey,
        child: ListView(
          children: <Widget>[
            AccountImage(),
            ListTile(
                leading: Icon(Icons.account_box, color: Colors.white),
                title: TextFormField(
                  onSaved: (input) => _name = input,
                  style: TextStyle(color: Colors.white),
                  decoration: InputDecoration(
                      fillColor: Colors.white,
                      hintText: "Name",
                      hintStyle: TextStyle(color: Colors.white)),
                )),
            ListTile(
              leading: Icon(Icons.email, color: Colors.white),
              title: TextFormField(
                style: TextStyle(color: Colors.white),
                decoration: InputDecoration(
                    fillColor: Colors.white,
                    hintText: "Email",
                    hintStyle: TextStyle(color: Colors.white)),
                // keyboardType: TextInputType.emailAddress,
                initialValue: _email,
                onSaved: (input) => _email = input,
              ),
            ),
            ListTile(
              leading: Icon(Icons.language, color: Colors.white),
              title: DropDownCountries(),
            ),
            Container(
              padding: EdgeInsets.all(15.0),
              child: Material(
                color: Colors.blue[700],
                elevation: 3.0,
                child: MaterialButton(
                  height: 45.0,
                  child: Text("Save", style: TextStyle(color: Colors.white)),
                  onPressed: () {
                    // updateData();
                    Navigator.of(context).pushReplacementNamed('/home_screen');
                  }
                ),
              ),
            )
          ],
        ),
        )
      ),
    );
  }
}

You can update the record like this you can get documentID from document

Firestore.instance
        .collection('users')
        .document(userID)// use documentID here to update particular document
        .updateData({
      "email": emailController.text,//This is the data i.e going to be updated
      "City": cityController.text,//This is the data i.e going to be updated
      "Phone": phoneNumberController.text.toString(),//This is the data i.e going to be updated
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM