在SQLite数据库混乱中搜索 [英] Searching in SQLite Database flutter
问题描述
如何使用TextField小部件作为搜索栏来查询本地SQLite数据库资产的结果?
How do I use a TextField widget as a search bar to query results from a local SQLite database asset?
有没有比使用文本框小部件更好的选择? 例子将不胜感激.
Would there be a better option than using a textfield widget? Examples would be much appreciated.
使用代码进行
padding: EdgeInsets.all(10.0),
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
child: new Container(
height: 70.0,
color: Theme.CompanyColors.iBlue,
child: new Padding(
padding: const EdgeInsets.all(8.0),
child: new Card(
child: new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
new Icon(Icons.search),
new Container(
width: MediaQuery.of(context).size.width - 100.0,
child: new TextField(
decoration: InputDecoration(
hintText: 'Search',
//onChanged:
//onSearchTextChanged,
),
),
),
这是搜索栏的代码
我的数据库中有一个表的句子,后面有一个段落ID,所以我想通过这样的查询进行搜索
my database has a table sentences attached with a paragraph_id, so i would want to search through a query like this
select * from sentences where title or body = userinput%
推荐答案
假设您使用的是此插件.您应该创建并填充数据库(插件的文档).
Assuming you're using this plugin. You should create and fill the database (plugin's docs).
然后,在搜索小部件中,使用以下示例:
Then, in the search widget, use below example:
class _MyHomePageState extends State<MyHomePage> {
Database database;
@override
void initState() {
// open the database
openDatabase('pathToDb', version: 1,
onCreate: (Database db, int version) async {
database = db;
// When creating the db, create the table
});
super.initState();
}
@override
Widget build(BuildContext context) {
if (database == null) {
return CircularProgressIndicator();
}
return Container(
padding: EdgeInsets.all(10.0),
child: Column(children: <Widget>[
Container(
padding: const EdgeInsets.all(8.0),
child: new Container(
height: 70.0,
child: new Padding(
padding: const EdgeInsets.all(8.0),
child: new Card(
child: new Container(
child: new Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: <Widget>[
new Icon(Icons.search),
new Container(
width: MediaQuery.of(context).size.width - 100.0,
child: new TextField(
decoration: InputDecoration(
hintText: 'Search',
//onSearchTextChanged,
),
onChanged: (String text) async {
List<Map> res = await database.rawQuery(
"SELECT * FROM sentences WHERE title LIKE '%${text}%' OR body LIKE '%${text}%'");
print(res);
}),
)
]))))))
]));
}
}
注意:如果多个窗口小部件可以访问数据库,请使用SQL帮助器.阅读文档"SQL帮助程序"部分.这个例子只是您的例子.
NOTE: If multiple widgets have access to DB, use SQL helpers. read the documents, section "SQL helpers". this example is just for your example.
这篇关于在SQLite数据库混乱中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!