Невозможно отобразить ListView из SqFLite - PullRequest
0 голосов
/ 19 января 2020

Мои данные могут загружаться в базу данных без каких-либо ошибок, однако я не могу отобразить мой список с данными.

Как вы можете видеть из функции _submit(), если есть ошибка, будет показана снэк-панель, указывающая на ошибку, и она не перейдет на главную страницу, однако в результате отобразится снэк-бар с сообщением об успехе,

Так что я подозреваю, что это связано с моим кодом просмотра списка или моим помощником по базам данных, поскольку я, возможно, что-то упустил в коде.
Любая помощь очень ценится!

Вот мой просмотр списка код:

FutureBuilder<List<Note>>(
  future: _databaseHelper.getNoteList(),
  builder: (BuildContext context, AsyncSnapshot<List<Note>> snapshot){
    if(snapshot.hasData){
       return  ListView.builder(
         itemCount: _count,
         itemBuilder: (BuildContext context, int position) {
           Note note = snapshot.data[position];
           return Card(
             color: Colors.white,
             elevation: 2.0,
             child: new ListTile(
               title: new Text(note.title),
               subtitle: new Text(note.bodyText),
               onTap: () =>
               _navigateToEditAddPage(note, 'Edit a Note'),
               onLongPress: () => _showDeleteDialog(note),
             ),
           );
        });
       }else{
         return Container(width: 0,height: 0,);
       }
   },),

Вот мой код insertData:

void _submit() async {
  if (_formKey.currentState.validate()) {
    note.title = _titleController.text;
    note.bodyText = _bodyTextController.text;
    note.date = _dateController.text;
    if (note.id == null) {
      int result = await _databaseHelper.insertData(note);
      if (result != 0) {
        _moveToHomePage('Note successfully added');
      } else {
          _showSnackBar('Note unable to be inserted due to some error');
        }
      } else {
          int result = await _databaseHelper.updateData(note);
          if (result != 0) {
            _moveToHomePage('Note successfully updated');
          } else {
              _showSnackBar('Note unable to be updated due to some error');
          }
        }
      }
     }

Вот мой код DatabaseHelper:

class DatabaseHelper {

  static Database _database;
  String dataTable = 'NoteTable';
  String colId = 'id';
  String colTitle = 'title';
  String colBody = 'bodyText';
  String colDate = 'date';

  DatabaseHelper._();
  static final DatabaseHelper db = 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 + 'notes.db';
    var notesDatabase =
        await openDatabase(path, version: 1, onCreate: _createDb);
    return notesDatabase;
  }

  void _createDb(Database database, int newVersion) async {
    await database.execute("CREATE TABLE $dataTable ("
    "$colId INTEGER PRIMARY KEY AUTOINCREMENT,"
    "$colTitle TEXT,"
    "$colBody TEXT,"
    "$colDate TEXT"
    ")");
  }

  Future<List<Map<String, dynamic>>> getNoteListMap() async {
    Database db = await this.database;
    var result = await db.query(dataTable);
    return result;
  }

  Future<int> insertData(Note note) async {
    Database db = await this.database;
    var result = await db.insert(dataTable,note.toMap(),conflictAlgorithm: 
    ConflictAlgorithm.replace,);
    return result;
  }

  Future<int> updateData(Note note) async {
    Database db = await this.database;
    var result = await db.update(dataTable,note.toMap(),
        where: 'colId = ?', whereArgs: [note.id]);
    return result;
  }

  Future<int> deleteData(Note note) async {
    Database db = await this.database;
    var result = await db
        .delete(dataTable, where: 'colId = ?', whereArgs: [note.id]);
    return result;
  }

  Future<int> getCount() async{
    Database db = await this.database;
    List<Map<String,dynamic>> x = await db.rawQuery('SELECT COUNT (*) from $dataTable');
    int result = Sqflite.firstIntValue(x);
    return result;
  }

  Future<List<Note>> getNoteList() async {
    var noteMapList = await getNoteListMap();
    int count = noteMapList.length;
    //list of notes, each note consist of their own independent variables
    List<Note> noteList;
    for (int i = 0; i < count; i++) {
      noteList.add(Note.fromMapObject(noteMapList[i]));
    }
    return noteList;
  }
}

И, наконец, моя модель Note:

class Note {
  int _id;
  String _date;
  String _title;
  String _bodyText;
  Note(this._date, this._title, this._bodyText);
  Note.withId(this._id, this._date, this._title, this._bodyText);

  set date(String date) {
    this._date = date;
  }

  get date => _date;

  set title(String title) {
    this._title = title;
  }

  get title => _title;

  set bodyText(String bodyText){
    this._bodyText = bodyText;
  }

  get bodyText => _bodyText;

  get id => _id;

  Map<String, dynamic> toMap() {
    var map = new Map<String, dynamic>();
    if (_id != null) {
      map['id'] = _id;
    }
    map['title'] = _title;
    map['bodyText'] = _bodyText;
    map['date'] = _date;
    return map;
  }

//Converting a map object to a note object
  Note.fromMapObject(Map<String,dynamic> fromMap){
    _id = fromMap['id'];
    _title = fromMap['title'];
    _bodyText = fromMap['bodyText'];
    _date = fromMap['date'];
  }
}

1 Ответ

0 голосов
/ 19 января 2020

Я обнаружил две ошибки в вашем коде.

1: в getNoteList () DatabaseHelper

List<Note> noteList;

до

List<Note> noteList = [];

2: в коде просмотра списка

itemCount: _count,

до

itemCount: snapshot.data.length,

результат:

result

...