KDC
KDC

Reputation: 611

Validator not saving data to Firebase database

im currently making a flutter project as a beginner and im kind of loving it. Now Im beginning to touch the backend (just a simple CREATE WRITE btw) the problem is when I input my data, it is null in Firebase

I think the problem is here in my TextFormFields validator

                    TextFormField(
                      decoration: InputDecoration(hintText: 'Enter Offer Name'),
                      validator: (value) {
                        if (value.isEmpty) {
                        }
                        return 'Please Enter Offer Name';
                      },
                      onSaved: (value) => offerName = value,
                    ),

I cant seem to find a way to fix this one up its only returning the text inside '' and not saving the actual input hence showing a null in Firebase Database

Additional details: I want the forms to save its data to firebase after clicking this FlatButton

                      child: FlatButton(
                        color: Colors.blue,
                        child: Text("Confirm", style: TextStyle(color: Colors.white)),
                        onPressed: () async {
                          await db.collection("createdoffers").add(
                            {
                              'name': offerName,
                              'type': offerType,
                              'start': start,
                              'end': end,
                            }
                          );
                        }
                      ),

Upvotes: 0

Views: 292

Answers (2)

Joshua de Guzman
Joshua de Guzman

Reputation: 2143

What went wrong

You are assigning the value of offerName inside the onSaved callback, but you never called .save() from the Form's FormState.

Example:

_formKey.currentState.save();

What you can do

Assuming that you are only after the validation of the input fields, and you are not fond of using TextEditingController, please see the setup below. I made the a simple app to demonstrate a simple way of validating and saving data base on your use case.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _usernameValue;
  String _passwordValue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Form(
              key: _formKey,
              child: Column(
                children: <Widget>[
                  TextFormField(
                    decoration: InputDecoration(hintText: "Username"),
                    // Callback when _formKey.currentState.validate(); is called
                    validator: (value) {
                      if (value.isEmpty) {
                        return "Username is required";
                      } else {
                        _usernameValue = value;
                        return null;
                      }
                    },
                  ),
                  TextFormField(
                    decoration: InputDecoration(hintText: "Password"),
                    obscureText: true,
                    // Callback when _formKey.currentState.validate(); is called
                    validator: (value) {
                      if (value.isEmpty) {
                        return "Password is required";
                      } else {
                        _passwordValue = value;
                        return null;
                      }
                    },
                  ),
                ],
              ),
            ),
            FlatButton(
              child: Text("Save"),
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  // Use the values here if the form with the unique form key has no errors
                  print("Username $_usernameValue");
                  print("Password $_passwordValue");

                  // TODO: Send data to firebase here
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

Hope this helps.

Further reading

Upvotes: 1

Peter Haddad
Peter Haddad

Reputation: 80924

The return statement in your code should be inside the if clause, currently it will always return Please enter some text since the return is outside the if. Therefore change the validator function to the following:

TextFormField(
  // The validator receives the text that the user has entered.
  validator: (value) {
    if (value.isEmpty) {
      return 'Please enter some text';
    }
    return null;
  },
);

Validate the input by providing a validator() function to the TextFormField. If the user’s input isn’t valid, the validator function returns a String containing an error message. If there are no errors, the validator must return null.

Upvotes: 1

Related Questions