如何在sqlite flutter中使用searchDelegate

时间:2019-01-09 22:59:28

标签: sqlite dart flutter

我创建了一个在sqlite数据库中存储一些注释的应用程序。我进行了所有CRUD操作,并且运行良好,但是当我尝试使用SearchDelegate在数据库中进行搜索操作时, 我有问题在使用SearchDelegate进行搜索之前,我将向您展示我的代码。

main.dart:

import 'package:flutter/material.dart';
import 'package:my_info/ui/home.dart';

void main() => runApp(
    MaterialApp(
        home: Home(),
        title: 'My notes',
        )
    );

databaseHelper:

 import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:my_info/model/notes.dart';
class DatabaseHelper{
  String tableName = 'info' ;
  String columnId = 'id' ;
  String columnTitle = 'title' ;
  String columnSubTitle = 'subTitle' ;
  String columnContent = 'conent' ;

  Database _db ;

  Future<Database> get db async {
    if(_db != null) return _db ;
    _db = await initDb();
    return _db ;
  }

  initDb()async{
    String databasePath = await getDatabasesPath();
    String path = join(databasePath,'info.db');
    var db = await openDatabase(path,version:1,onCreate: _onCreate);
    return db;
  }

  _onCreate(Database db, int newVersion) async{
    var sql = "CREATE TABLE $tableName ($columnId INTEGER PRIMARY KEY ,"
        "$columnTitle TEXT, $columnSubTitle TEXT, $columnContent TEXT)" ;
    await db.execute(sql);
  }

  Future<int> saveNote(Notes note)async{
    var dbClient = await db ;
    var result = await dbClient.insert(tableName,
        note.toMap());
    return result ;
  }

  Future<int> getCount()async{
    var dbClient = await db;
    return Sqflite.firstIntValue(await dbClient.rawQuery('SELECT COUNT(*) FROM $tableName'));
  }

  Future<List> getAllNotes() async{
    var dbClient = await db ;
    List result = await dbClient.query(tableName,
        columns: [
          columnId,columnTitle, columnSubTitle,columnContent
        ]);
    return result.toList() ;
  }

  Future<Notes> searchNotes(String title) async{
    var dbClient = await db ;
    var result = await dbClient.rawQuery(
      ' select * from $tableName WHERE $columnTitle LIKE %$title% '
    );
    if(result.length > 0 ) return Notes.fromMap(result.first);
    return null ;
  }

  Future<Notes> getNote(int id)async{
    var dbClient = await db ;
    List<Map> result = await dbClient.query(tableName,
        columns: [
          columnTitle, columnSubTitle,columnContent
        ],
        where: '$columnId = ?', whereArgs: [id]);
    if(result.length > 0 ) return new Notes.fromMap(result.first);

    return null ;
  }


  Future<int> updateNote(Notes note) async{
    var dbClient = await db ;
    return await dbClient.update(tableName, note.toMap(),
        where: '$columnId = ? ',
        whereArgs: [note.id]);
  }

  Future<int> deleteNote(int id)async{
    var dbClient = await db ;
    return await dbClient.delete(tableName,
        where: '$columnId = ? ', whereArgs: [id]);
  }

  Future closeDb()async{
    var dbClient = await db ;
    dbClient.close();
  }
}

课堂笔记

class Notes{
  int _id;
  String _title;
  String _subTitle;
  String _content;

  Notes(this._title,this._subTitle,this._content);
  Notes.map(dynamic obj){
    this._id = obj['id'];
    this._title = obj['title'];
    this._subTitle = obj['subTitle'];
    this._content = obj['conent'];
  }

  int get id => _id;
  String get title => _title;
  String get subTitle => _subTitle;
  String get content => _content;

  Map<String,dynamic> toMap(){
    Map map = Map<String,dynamic>();
    if(id == null) {
      map['id'] = _id ;
    }
    map['title'] = _title;
    map['subTitle'] = _subTitle;
    map['conent'] = _content ;

    return map;
  }


  Notes.fromMap(Map<String,dynamic>map){
    this._id = map['id'];
    this._title = map['title'];
    this._subTitle = map['subTitle'];
    this._content = map['conent'];
  }

}

首页

import 'package:flutter/material.dart';
import 'package:my_info/model/notes.dart';
import 'package:my_info/utils/database_helper.dart';
import 'package:my_info/ui/notes_screen.dart';
class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => HomeState();

}

class HomeState extends State<Home>{
  List<Notes> items = new List();
  DatabaseHelper db = new DatabaseHelper();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
      db.getAllNotes().then((notes){
        setState(() {
          notes.forEach((note){
            items.add(Notes.fromMap(note));
          });
        });
      });

  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.deepPurple,
        title: Text('Notes',
          style: TextStyle(
              fontStyle: FontStyle.italic,
              fontWeight: FontWeight.w700,
              fontSize: 30
          ),
        ),
        centerTitle: true,

      ),
      body: Center(
        child:ListView.builder(
          itemCount: items.length,
          padding: EdgeInsets.all(15),
          itemBuilder: (context,int position){

            return Column(
              children: <Widget>[

                Divider(height: 5,),
                Row(
                  children: <Widget>[

                    Expanded(
                        child: ListTile(
                      title: Text(items[position].title,
                        style: TextStyle(
                            fontSize: 22,
                            fontWeight: FontWeight.bold,
                            color: Colors.redAccent
                        ),
                      ),
                      subtitle: Text(items[position].subTitle,
                        style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            fontStyle: FontStyle.italic
                        ),
                      ),
                      leading: Column(
                        children: <Widget>[
                          CircleAvatar(
                            backgroundColor: Colors.deepPurple,
                            radius: 25,
                            child:  Icon(Icons.insert_comment,
                            color: Colors.deepOrange,)
                            //Image.asset('images/information.png'),
                          )
                        ],
                      ),
                      onTap: ()=> _navigateToNoteScreen(context,items[position]),
                    )
                    ),
                    IconButton(icon: Icon(Icons.delete,size: 30,
                    color: Colors.redAccent,),
                        onPressed: () => _showDialog(context,items[position],position)
                    )
                  ],
                )

              ],
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(child: Icon(Icons.add),
          backgroundColor: Colors.deepPurple,
          onPressed: () => _createNote(context)
    ),
    );
  }

  _navigateToNoteScreen(BuildContext context,Notes note)async{
    String result = await Navigator.push(context,
        MaterialPageRoute(builder: (context) => NoteScreen(note)));
    if(result == 'update'){
      db.getAllNotes().then((note){
        setState(() {
          items.clear();
          note.forEach((notes){
            items.add(Notes.fromMap(notes));
          });
        });
      });
    }
  }

  _deleteNote(BuildContext context,Notes note, int position){
    db.deleteNote(note.id).then((notes){
      setState(() {
       items.removeAt(position);
      });
    });
    Navigator.of(context).pop();
  }

  void _createNote(BuildContext context)async{
    String result = await Navigator.push(context,
        MaterialPageRoute(builder: (context) =>
            NoteScreen(
                Notes('','','')
            )
        )
    );

    if(result == 'save'){
      db.getAllNotes().then((notes){
        setState(() {
          items.clear();
          notes.forEach((note){
            items.add(Notes.fromMap(note));
          });
        });
      });
    }
  }

  void _showDialog(BuildContext context,Notes note, int position) {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Delete ?"),
          content: new Text("Do you want delete Content"),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("Noا"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),

            new FlatButton(
              child: new Text("Yes"),
              onPressed: () {
                _deleteNote(context,items[position],position);
              },
            ),
          ],
        );
      },
    );
  }



}

在CRUD上,一切正常,我要添加3条记录 但是当我使用SearchDelegate进行搜索时, 我遇到了一些错误,但从该错误中我找不到任何有用的东西来得到想要的东西。  现在,在尝试搜索后,我将向您显示代码。

import 'package:flutter/material.dart';
import 'package:my_info/model/notes.dart';
import 'package:my_info/utils/database_helper.dart';
import 'package:my_info/ui/notes_screen.dart';
class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => HomeState();

}

class HomeState extends State<Home>{
  List<Notes> items = new List();
  DatabaseHelper db = new DatabaseHelper();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    db.getAllNotes().then((notes){
      setState(() {
        notes.forEach((note){
          items.add(Notes.fromMap(note));
        });
      });
    });

  }


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.deepPurple,
        title: Text('Notes',
          style: TextStyle(
              fontStyle: FontStyle.italic,
              fontWeight: FontWeight.w700,
              fontSize: 30
          ),
        ),
        centerTitle: true,
        actions: <Widget>[
          IconButton(icon: Icon(Icons.search,
            color: Colors.white,), onPressed: (){
            showSearch(context: context, delegate: DataSearch());
          })
        ],
      ),
      /*body: Center(
        child:ListView.builder(
          itemCount: items.length,
          padding: EdgeInsets.all(15),
          itemBuilder: (context,int position){

            return Column(
              children: <Widget>[

                Divider(height: 5,),
                Row(
                  children: <Widget>[

                    Expanded(
                        child: ListTile(
                      title: Text(items[position].title,
                        style: TextStyle(
                            fontSize: 22,
                            fontWeight: FontWeight.bold,
                            color: Colors.redAccent
                        ),
                      ),
                      subtitle: Text(items[position].subTitle,
                        style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            fontStyle: FontStyle.italic
                        ),
                      ),
                      leading: Column(
                        children: <Widget>[
                          CircleAvatar(
                            backgroundColor: Colors.deepPurple,
                            radius: 25,
                            child:  Icon(Icons.insert_comment,
                            color: Colors.deepOrange,)
                            //Image.asset('images/information.png'),
                          )
                        ],
                      ),
                      onTap: ()=> _navigateToNoteScreen(context,items[position]),
                    )
                    ),
                    IconButton(icon: Icon(Icons.delete,size: 30,
                    color: Colors.redAccent,),
                        onPressed: () => _showDialog(context,items[position],position)
                    )
                  ],
                )

              ],
            );
          },
        ),
      ),*/
      floatingActionButton: FloatingActionButton(child: Icon(Icons.add),
          backgroundColor: Colors.deepPurple,
          onPressed: null  /*() => _createNote(context)*/
      ),
    );
  }

/* _navigateToNoteScreen(BuildContext context,Notes note)async{
    String result = await Navigator.push(context,
        MaterialPageRoute(builder: (context) => NoteScreen(note)));
    if(result == 'update'){
      db.getAllNotes().then((note){
        setState(() {
          items.clear();
          note.forEach((notes){
            items.add(Notes.fromMap(notes));
          });
        });
      });
    }
  }

  _deleteNote(BuildContext context,Notes note, int position){
    db.deleteNote(note.id).then((notes){
      setState(() {
       items.removeAt(position);
      });
    });
    Navigator.of(context).pop();
  }

  void _createNote(BuildContext context)async{
    String result = await Navigator.push(context,
        MaterialPageRoute(builder: (context) =>
            NoteScreen(
                Notes('','','')
            )
        )
    );

    if(result == 'save'){
      db.getAllNotes().then((notes){
        setState(() {
          items.clear();
          notes.forEach((note){
            items.add(Notes.fromMap(note));
          });
        });
      });
    }
  }

  void _showDialog(BuildContext context,Notes note, int position) {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Delete"),
          content: new Text("Do you wand delete content"),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("NO"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),

            new FlatButton(
              child: new Text("YES"),
              onPressed: () {
                _deleteNote(context,items[position],position);
              },
            ),
          ],
        );
      },
    );
  }
*/


}

class DataSearch extends SearchDelegate<Notes> {
  DatabaseHelper db = new DatabaseHelper();

  List<Notes> items = new List();
  List<Notes> suggestion = new List();
  HomeState i = HomeState();



  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(icon: Icon(Icons.clear), onPressed: () {
        query = '';
      } )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: (){
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    suggestion = query.isEmpty ? i.items : i.items;/*.where((target) =>
        target.title.startsWith(query))*/
    if( i.items.isEmpty)
    {
      print("Null");
    }
    return ListView.builder(
      itemBuilder: (context, position)=>
          ListTile(
            leading: Icon(Icons.location_city),
            title: Text('${i.items[position].title}'),

          ),
      itemCount: suggestion.length,
    );

  }
}

现在,运行该应用程序后,当我单击搜索图标时,它不显示任何内容,并且列表中有3条记录,但不显示任何内容。 我希望你能帮助我。我真的找了一个星期的解决方案 抱歉,我的英语不好,这是我第一次在StackOverflow中提问。

谢谢。

1 个答案:

答案 0 :(得分:0)

你好,我认为您必须将数据发送到datasearch类。

IconButton(icon: Icon(Icons.search,
    color: Colors.white,),onPressed: 
(){
    showSearch(context: context, 
delegate: DataSearch(this.items));
})

然后在DataSearch类中添加此

DataSearch({@required this.items});

在DataSearch类更改中

List<Notes> items = new List(); => final List<Notes> items = new List();