How can I reslove The method 'toMap' was called on null?

447

Your object of AddressModel has never been initialized in _MyHomePageState, it has just been declared. You need to initialize it if you want to use that object. You can do that this way.

class _MyHomePageState extends State<MyHomePage> {
  AddressModel model = AddressModel("PIN");
  ...
}
Share:
447
Jorden
Author by

Jorden

Updated on December 17, 2022

Comments

  • Jorden
    Jorden over 1 year

    Why I am getting Unhandled Exception: NoSuchMethodError: The method 'toMap' was called on null this error. I stuck here but I can't understand my mistake. I think the instance of model class is not getting but Iknow why it is happening.

    Model Class

    class AddressModel {
    
      int _id;
      String _pin;
    
      AddressModel(this._pin);
    
    
      int get id => _id;
    
      set id(int value) {
        this._id = value;
      }
    
      Map<String, dynamic> toMap() {
        var map = Map<String, dynamic>();
        if (_id != null) {
          map['id'] = _id;
        }
        map['pincode'] = _pin;
    
        return map;
      }
    
      String get pin => _pin;
    
      set pin(String value) {
       this._pin = value;
      }
    
    }
    

    Database

    class DatabaseHelper{
    
      DatabaseHelper();
    
      static final DatabaseHelper db = DatabaseHelper();
      Database _database;
    
      String addressTable = 'address';
      String addressId = 'id';
      String pinCodeColumn = 'pincode';
    
    
      Future<Database> get database async {
        if (_database != null) return _database;
        _database = await getDatabaseInstance();
        return _database;
      }
    
      Future<Database> getDatabaseInstance() async {
        Directory directory = await getApplicationDocumentsDirectory();
        String path = join(directory.path, "student.db");
        return await openDatabase(path, version: 1,onCreate: _createDb);
      }
    
      void _createDb(Database db, int newVersion) async {
    
        await db.execute('CREATE TABLE $addressTable ($addressId INTEGER PRIMARY KEY AUTOINCREMENT, $pinCodeColumn TEXT)');
    
      }
      Future<int> insertData(AddressModel note) async {
        Database db = await this.database;
        var result = await db.insert(addressTable, note.toMap());
        return result;
      }
    
    }
    
    
    

    Main Class

    class _MyHomePageState extends State<MyHomePage> {
      AddressModel model;
      TextEditingController pinCode = TextEditingController();
      DatabaseHelper helper = DatabaseHelper();
    
      @override
      Widget build(BuildContext context) {
    
        return Scaffold(
          appBar: AppBar(
    
            title: Text(widget.title),
          ),
          body: Center(
            // Center is a layout widget. It takes a single child and positions it
            // in the middle of the parent.
            child: Column(
    
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                  child: TextField(
                    keyboardType: TextInputType.phone,
                    controller: pinCode,
                    onChanged: (value) {
                      debugPrint('Something changed in Title Text Field');
                      updatePin();
                    },
                    decoration: InputDecoration(
                        labelText: 'Pin Code *',
                        hintText: 'Fill your Pin Code',
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0))),
                  ),
                ),
                RaisedButton(
                  onPressed: (){
                    helper.insertData(model);
                  },
                )
              ],
            ),
          ), 
        );
      }
      void updatePin(){
        model.pin = pinCode.text;
      }
    }
    
    

    This is the error

    E/flutter (31607): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'toMap' was called on null.
    E/flutter (31607): Receiver: null
    E/flutter (31607): Tried calling: toMap()
    E/flutter (31607): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
    E/flutter (31607): #1      DatabaseHelper.insertProject (package:xpecto_teasoko/databasee.dart:50:53)