未处理的异常:NoSuchMethodError:在null上调用了方法'insertData'

时间:2020-01-02 06:40:28

标签: java android flutter dart sqflite

尝试获取并将位置存储在本地数据库中时出现此错误 这是我的主页。飞镖

import 'package:attendance_app/local_database/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:intl/intl.dart';
import 'package:toast/toast.dart';
import 'package:attendance_app/local_database/database.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _buttonEnabled = true;
  Position _currentPosition;
  String _formattedDate;
  DataBaseHelper helper;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getCurrentLocation();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            widget.title,
            style: TextStyle(color: Colors.white),
          ),
        ),
        body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  height: 55.0,
                  width: 150.0,
                  color: Colors.lightGreen,
                  child: RaisedButton(
                    elevation: 0,
                    textColor: Colors.white,
                    splashColor: Colors.amber,
                    disabledColor: Colors.grey,
                    child: Text(
                      "Head start",
                      textScaleFactor: 1.6,
                    ),
                    color: Colors.lightGreen,
                    onPressed: () async {
                      _getCurrentLocation();
                      _getDateTime();
                      _insertToDb(createDataBaseObj(
                          'IN',
                          _currentPosition.latitude.toString(),
                          _currentPosition.longitude.toString(),
                          _formattedDate));
                      Toast.show("$_currentPosition , $_formattedDate", context,
                          duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
                    },
                  ),
                ),
                SizedBox(
                  height: 20.0,
                ),
                Container(
                    height: 55.0,
                    width: 150.0,
                    color: Colors.red[300],
                    child: RaisedButton(
                      elevation: 0,
                      textColor: Colors.white,
                      splashColor: Colors.amber,
                      disabledColor: Colors.grey,
                      child: Text(
                        "Check out",
                        textScaleFactor: 1.6,
                      ),
                      color: Colors.red[300],
                      onPressed: () async {
                        _getCurrentLocation();
                        _getDateTime();
                        _insertToDb(createDataBaseObj(
                          'OUT',
                          _currentPosition.latitude.toString(),
                          _currentPosition.longitude.toString(),
                          _formattedDate));
                        Toast.show(
                            "$_currentPosition , $_formattedDate", context,
                            duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
                      },
                    )),
              ]),
        ),
        bottomNavigationBar: Container(
            height: 55.0,
            color: _buttonEnabled ? Colors.green : Colors.grey,
            child: RaisedButton(
              elevation: 0,
              textColor: Colors.white,
              splashColor: Colors.amber,
              disabledColor: Colors.grey,
              child: Text(
                "sync",
                textScaleFactor: 1.6,
              ),
              color: Colors.green,
              onPressed: () async {},
            )));
  }

  _getCurrentLocation() async {
    final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
    await geolocator
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      print(position);
      setState(() {
        _currentPosition = position;
      });
    }).catchError((e) {
      print(e);
    });
  }

  _getDateTime() {
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('kk:mm:ss EEE d MMM').format(now);
    setState(() {
      _formattedDate = formattedDate;
    });
  }

  DataBase createDataBaseObj(type, lat, long, time) {
    DataBase result = DataBase(type, lat, long, time);
    print('createDataBaseObj');
    print(result.toMap());
    return result;
  }

  void _insertToDb(DataBase dataBase) async {
    var value = await helper.insertData(dataBase);
    print(value);
  }

  void _delete(BuildContext context, DataBase dataBase) async {
    await helper.deleteData(dataBase.id);
  }
}

这是database_helper.dart文件

import 'package:sqflite/sqflite.dart';
import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'database.dart';

class DataBaseHelper {
  static DataBaseHelper _dataBaseHelper;
  static Database _database;

  String table = 'attendance';
  String id = 'id';
  String type = 'type';
  String latitude = 'latitude';
  String longitude = 'longitude';
  String time = 'time_stamp';

  DataBaseHelper._createInstance();
  factory DataBaseHelper() {
    if (_dataBaseHelper == null) {
      _dataBaseHelper = DataBaseHelper._createInstance();
    }
    return _dataBaseHelper;
  }
  Future<Database> get database async{
    if (_database == null){
      _database = await initializeDatabase();
    }
    return _database;
  }
  Future<Database> initializeDatabase() async{

    Directory directory = await getApplicationDocumentsDirectory();
    String path = directory.path + 'attendance.db';
    print(path);

    var attendanceDb = await openDatabase(path,version: 1,onCreate: _createDb);
    return attendanceDb;
  }
  // Create Table
  void _createDb(Database db,int newVersion) async{
    await db.execute('CREATE TABLE $table($id INTEGER PRIMARY KEY AUTOINCREMENT, $type TEXT,$latitude TEXT, $longitude TEXT, $time TEXT)');
  }
  // Fetch data from DB
  Future<List<Map<String, String>>> getDatafromdb() async{
    Database db = await this.database;
    var result = await db.query(this.table);
    return result;
  }




  // Insert data to DB
  Future<int> insertData(DataBase dataBase) async{
    var db = await this.database;
    print('database');
    print(db);
    var result = await db.insert(this.table, dataBase.toMap());
    return result;
  }
  // Delete data from DB
  Future<int> deleteData(int Id) async{
    var db = await this.database;
    var result = await db.rawDelete('DELETE FROM $table WHERE $id = $Id');
    return result;
  }
}

错误

An Observatory debugger and profiler on CPH1853 is available at:
http://127.0.0.1:43427/vxgmPQJhR4E=/
For a more detailed help message, press "h". To detach, press "d"; to quit,
press "q".
I/flutter (27382): createDataBaseObj
I/flutter (27382): {type: IN, latitude: 11.1115482, longitude: 77.3637584, timeStamp: 12:09:29 Thu 2 Jan}
E/flutter (27382): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'insertData' was called on null.
E/flutter (27382): Receiver: null
E/flutter (27382): Tried calling: insertData(Instance of 'DataBase')
E/flutter (27382): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (27382): #1      _MyHomePageState._insertToDb (package:attendance_app/screens/homepage.dart:147:30)
E/flutter (27382): #2      _MyHomePageState.build.<anonymous closure> (package:attendance_app/screens/homepage.dart:58:23)
E/flutter (27382): #3      _AsyncAwaitCompleter.start (dart:async-patch/async_patch.dart:45:6)
E/flutter (27382): #4      _MyHomePageState.build.<anonymous closure> (package:attendance_app/screens/homepage.dart:55:32)
E/flutter (27382): #5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (27382): #6      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (27382): #7      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (27382): #8      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (27382): #9      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (27382): #10     BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (27382): #11     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (27382): #12     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (27382): #13     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (27382): #14     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (27382): #15     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (27382): #16     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (27382): #17     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (27382): #18     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (27382): #19     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (27382): #20     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (27382): #21     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (27382): #22     _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (27382): #23     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (27382): #24     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (27382): #25     _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (27382): #26     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (27382): 
I/flutter (27382): Lat: 11.1115482, Long: 77.3637584
Application finished.

1 个答案:

答案 0 :(得分:1)

您可能需要在 MyHomePage 中初始化DataBaseHelper

 helper = DataBaseHelper();