удалить базу данных при выходе и создать заново после входа в дартс - PullRequest
0 голосов
/ 25 марта 2020

Я занимаюсь разработкой приложения на Flutter and dart, используя базу данных SQFLite и Firestore. Я хочу, чтобы пользователь нажимал кнопку выхода из системы, приложение удаляло базу данных sqflite и возвращало пользователя на экран входа в систему, а когда вход в систему извлекал данные информация о пользователе авторизуется из Firestore , и он удаляет БД, но проблема в том, что когда я хочу снова войти в приложение, он показывает мне эту ошибку ..

Пожалуйста, нужна помощь

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: DatabaseException(database_closed 1)
#0      wrapDatabaseException (package:sqflite/src/exception_impl.dart:12:7)
E/flutter (28706): <asynchronous suspension>
E/flutter (28706): #1      SqfliteDatabaseFactoryImpl.wrapDatabaseException 
(package:sqflite/src/factory_impl.dart:25:7)
E/flutter (28706): #2      SqfliteDatabaseMixin.safeInvokeMethod 
 (package:sqflite/src/database_mixin.dart:188:15)
  E/flutter (28706): #3      SqfliteDatabaseMixin.txnRawInsert.<anonymous closure> 
 (package:sqflite/src/database_mixin.dart:363:14)
E/flutter (28706): #4      SqfliteDatabaseMixin.txnSynchronized.<anonymous closure> 
(package:sqflite/src/database_mixin.dart:307:22)
E/flutter (28706): #5      BasicLock.synchronized (package:synchronized/src/basic_lock.dart:32:26)
E/flutter (28706): #6      SqfliteDatabaseMixin.txnSynchronized 
(package:sqflite/src/database_mixin.dart:303:43)
E/flutter (28706): #7      SqfliteDatabaseMixin.txnWriteSynchronized 
(package:sqflite/src/database_mixin.dart:325:7)
E/flutter (28706): #8      SqfliteDatabaseMixin.txnRawInsert 
(package:sqflite/src/database_mixin.dart:362:12)
E/flutter (28706): #9      SqfliteDatabaseExecutorMixin.rawInsert 
(package:sqflite/src/database_mixin.dart:49:15)
E/flutter (28706): #10     SqfliteDatabaseExecutorMixin.insert 
 (package:sqflite/src/database_mixin.dart:59:12)
E/flutter (28706): #11     SQFliteDBHelper.SAVE_USER 
(package:health_calorie_db/settings_in_app/sqflite_db_helper.dart:86:20)
E/flutter (28706): <asynchronous suspension>
E/flutter (28706): #12     userServices.saveToSQFLiteDB 
(package:health_calorie_db/dbServicesManager/userServices.dart:72:13)
E/flutter (28706): #13     userServices.logInCheck 
(package:health_calorie_db/dbServicesManager/userServices.dart:99:10)
E/flutter (28706): <asynchronous suspension>
E/flutter (28706): #14     loginState.checkValidationForms 
(package:health_calorie_db/ui_classes/log_in_up_pages/log_in_page.dart:25:22)
E/flutter (28706): #15     loginState.build.<anonymous closure>.<anonymous closure> 
(package:health_calorie_db/ui_classes/log_in_up_pages/log_in_page.dart:112:60)
E/flutter (28706): #16     _createButton.build.<anonymous closure> 
(package:health_calorie_db/ui_classes/log_in_up_pages/log_in_page.dart:165:9)
E/flutter (28706): #17     _InkResponseState._handleTap 
(package:flutter/src/material/ink_well.dart:706:14)
E/flutter (28706): #18     _InkResponseState.build.<anonymous closure> 
 (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (28706): #19     GestureRecognizer.invokeCallback 
(package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (28706): #20     TapGestureRecognizer.handleTapUp 
(package:flutter/src/gestures/tap.dart:486:11)
E/flutter (28706): #21     BaseTapGestureRecognizer._checkUp 
(package:flutter/src/gestures/tap.dart:264:5)
E/flutter (28706): #22     BaseTapGestureRecognizer.acceptGesture 
 (package:flutter/src/gestures/tap.dart:236:7)
E/flutter (28706): #23     GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
E/flutter (28706): #24     GestureBinding.handleEvent 
 (package:flutter/src/gestures/binding.dart:222:20)
E/flutter (28706): #25     GestureBinding.dispatchEvent 
(package:flutter/src/gestures/binding.dart:198:22)
E/flutter (28706): #26     GestureBinding._handlePointerEvent 
 (package:flutter/src/gestures/binding.dart:156:7)
 E/flutter (28706): #27     GestureBinding._flushPointerEventQueue 
 (package:flutter/src/gestures/binding.dart:102:7)
  E/flutter (28706): #28     GestureBinding._handlePointerDataPacket 
 (package:flutter/src/gestures/binding.dart:86:7)
 E/flutter (28706): #29     _rootRunUnary (dart:async/zone.dart:1138:13)
 E/flutter (28706): #30     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
 E/flutter (28706): #31     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
 E/flutter (28706): #32     _invoke1 (dart:ui/hooks.dart:273:10)
 E/flutter (28706): #33     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)

и вот код

 FlatButton(
            child: Text('Yes'),
            onPressed: ()async {
              setState(() {
                dbHelper.deleteDB();
                var duration = new Duration(seconds: 8);
                return new Timer(duration, (){
                  exitApp();
                });
              });
            },

Future<bool> deleteDB() async {
  try{
 deleteDatabase(path);
 }catch( e){
 print(e.toString());
}
 print('deleting db');
}

  exitApp()async {
  Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (context)=>login()), 
  (Route<dynamic> route) => false);
}


Future logInCheck(String name , String email, BuildContext buildContext) async
{
  userModel user ;
  final QuerySnapshot result = await userCollection.where('user_email', isEqualTo: email)
    .where('user_name' , isEqualTo: name).limit(1).getDocuments(); // searching for a particular user

  if(result.documents .length > 0){
  final List<DocumentSnapshot> ds = result.documents;
  for(int i=0; i< 1; i++ )
  {
     user = new userModel(ds[i].documentID, ds[i]['user_name'],ds[i]['user_email'],
     ds[i]['user_gender'],
     ds[i]['user_weight'],ds[i]['user_height'] ,ds[i]['cityPoint'] ,ds[i]['checkLogIn']);
     print(user.user_email + '  :  ' +user.user_id);
     saveToSQFLiteDB(user);
     print('Added');
 }
nav.HOMEnavigate(buildContext,email);
} // if

else{
  String msg = 'Couldnt find user with email \n fill with correct info' ;
  nav.showSnackBar(buildContext , msg);
}

}

void saveToSQFLiteDB(userModel user) {

  userInApp u = new userInApp(user.user_id, user.user_name, user.user_email, user.user_weight,
   user.user_height, user.cityPoint.latitude, user.cityPoint.longitude,user.checkLogIN);
  dbHelper.SAVE_USER(u);
  }


 Future<userInApp> SAVE_USER (userInApp user) async{
  var dbClient = await datebase;
//user.user_id =
  await dbClient.insert(userTable, user.toMap()).toString();
  print('user has been saved');
  return user;

}

1 Ответ

0 голосов
/ 26 марта 2020

Я обнаружил проблему, я должен установить db = null перед удалением db. Когда я изменяю метод deleteDB на это, я работал как хочу .. Спасибо

  Future<void> deleteDB() async {
   try{
    print('deleting db');
    db=null;
    deleteDatabase(path);
    }catch( e){
    print(e.toString());
     }

print('db is deleted');
}
...