【问题标题】:How can I reslove The method 'toMap' was called on null?如何解决在 null 上调用了“toMap”方法?
【发布时间】:2020-05-06 19:43:35
【问题描述】:

为什么我收到Unhandled Exception: NoSuchMethodError: The method 'toMap' was called on null 这个错误。我卡在这里,但我无法理解我的错误。我认为模型类的实例没有得到,但我知道它为什么会发生。

模型类

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;
  }

}

数据库

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;
  }

}


主类

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;
  }
}

这是错误

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)

【问题讨论】:

    标签: android ios sqlite flutter dart


    【解决方案1】:

    您的 AddressModel 对象从未在 _MyHomePageState 中初始化,它刚刚被声明。如果要使用该对象,则需要对其进行初始化。你可以这样做。

    class _MyHomePageState extends State<MyHomePage> {
      AddressModel model = AddressModel("PIN");
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 2021-01-30
      • 2020-04-25
      • 2021-02-05
      • 2023-03-08
      • 2019-11-05
      • 2020-06-12
      • 2021-12-28
      • 2021-08-14
      相关资源
      最近更新 更多