Home > Mobile >  The setter 'firstName=' was called on null. Receiver: null Tried calling: firstName="
The setter 'firstName=' was called on null. Receiver: null Tried calling: firstName="

Time:12-13

Someone please help me, I am stuck on this error since last two days, what I am trying send data from input form using on clicking on a button to the lists, when clicked on a button, a form opens on the same page but when I input the data in form and clicks the submit button, nothing happens and on terminal it shows The setter 'firstName=' was called on null. Receiver: null Tried calling: firstName="hfjfhd".

this is my model.dart file class Model { string firstName = ""; String lastName = ""; String email = ""; String password = ""; Model({this.firstName, this.lastName, this.email, this.password});}

and this is my main file on which i am opening the form and showing the result.

import 'package:flutter/material.dart';
import 'model.dart';
import 'package:dummy_project/components/save_data_from_input_into_object/form.dart';
import 'package:dummy_project/components/save_data_from_input_into_object/result.dart';

class DialogForm extends StatefulWidget {
  List<Model> models = <Model>[];
  Model tempModel;

  DialogForm();

  @override
  State<DialogForm> createState() => _ResultState();
  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<Model>('model', tempModel));
  }
}

class _ResultState extends State<DialogForm> {
  final _formKey = GlobalKey<FormState>();

  @override

  
  Widget build(BuildContext context) {
    return (Scaffold(
      appBar: AppBar(title: Text('Successful')),
      
      body: Container(
        margin: EdgeInsets.all(10.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            
            Flexible(
              child: ListView.builder(
                itemCount: widget.models.length,
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(widget.models[index].firstName),
                    subtitle: Text(widget.models[index].lastName),
                    trailing: Text(widget.models[index].email),
                  );
                },
              ),
            ),

            Align(
              child: RaisedButton(
                child: Text('Click Me!'),
                  onPressed: (){
                showDialog(
                    context: context,
                    builder: (BuildContext context){
                      return AlertDialog(
                        content: Stack(
                          overflow: Overflow.visible,
                          children: <Widget>[
                            Positioned(
                              right: -40,
                              top: -40,
                              child: InkResponse(
                                onTap: () {
                                  Navigator.of(context).pop();
                                },
                                child: CircleAvatar(
                                  child: Icon(Icons.close),
                                  backgroundColor: Colors.red,
                                ),
                              ),
                            ),
                            Form(
                                key: _formKey,
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: <Widget>[
                                    Padding(
                                      padding: EdgeInsets.all(8.0),
                                      child: MyTextFormField(
                                        hintText: 'First Name',
                                        validator: (String value) {
                                          if (value.isEmpty) {
                                            return 'Enter your first name';
                                          }
                                          return null;
                                        },
                                        onSaved: (String value) {
                                          widget.tempModel.firstName = value;
                                        },
                                      ),
                                    ),
                                    Padding(
                                      padding: EdgeInsets.all(8.0),
                                      child: MyTextFormField(
                                        hintText: 'Last Name',
                                        validator: (String value) {
                                          if (value.isEmpty) {
                                            return 'Enter your last name';
                                          }
                                          return null;
                                        },
                                        onSaved: (String value) {
                                          widget.tempModel.lastName = value;
                                        },
                                      ),
                                    ),
                                    Padding(
                                      padding: EdgeInsets.all(8.0),
                                      child: MyTextFormField(
                                        hintText: 'Enter email',
                                        isEmail: true,
                                        // validator: (String value) {
                                        //   if (!validator.isEmail(value)) {
                                        //     return 'Please enter a valid email';
                                        //   }
                                        //   return null;
                                        // },
                                        onSaved: (String value) {
                                          widget.tempModel.email = value;
                                        },
                                      ),
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: RaisedButton(
                                        child: Text("Submit"),
                                        onPressed: () {
                                          if (_formKey.currentState.validate()) {
                                            _formKey.currentState.save();
                                            widget.models.add(widget.tempModel);
                                            Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                    builder: (context) => DialogForm()));
                                          }
                                        },
                                      ),
                                    )
                                  ],
                                )
                            ),
                          ],
                        ),
                      );
                    }

                );
              }

              ),
              alignment: Alignment.bottomRight,
            ),
          ],

        ),
      ),
    )
    );
  }
}

class MyTextFormField extends StatelessWidget {
  final String hintText;
  final Function validator;
  final Function onSaved;
  final bool isPassword;
  final bool isEmail;

  MyTextFormField({
    this.hintText,
    this.validator,
    this.onSaved,
    this.isPassword = false,
    this.isEmail = false,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8.0),
      child: TextFormField(
        decoration: InputDecoration(
          hintText: hintText,
          contentPadding: EdgeInsets.all(15.0),
          border: InputBorder.none,
          filled: true,
          fillColor: Colors.grey[200],
        ),
        obscureText: isPassword ? true : false,
        validator: validator,
        onSaved: onSaved,
        keyboardType: isEmail ? TextInputType.emailAddress : TextInputType.text,
      ),
    );
  }
}```

CodePudding user response:

Make it nullable : "?" here states that it can be null by default or by any operation.

Suggestions : use textEditingController to get input value, and pass it. and use null safe check when showing texts from model, cause you defined it as null.

widget.models[index].firstName ?? "First Name"

above, "??" means if left statement is in any case is null, then right statement will get executed, so if you are getting "First Name" in your text field then its getting null from model.

class Model{

String? firstName;
String? lastName;
String? email;
String? password;

Model({
 this.firstName,
 this.lastName,
 this.email,
 this.password
});
}

Pl let me know if you have any doubts Thanks

CodePudding user response:

You don't initialise tempModel, so it will be null, that's why you get the error message for example at widget.tempModel.firstName.

Instead of Model tempModel; try:

Model tempModel = Model();

or

final tempModel = Model();
  • Related