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.
edit with code:
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,
),
),
),
This is the code for the searchbar
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%
Solution 1: Yamin
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);
}),
)
]))))))
]));
}
}
NOTE: If multiple widgets have access to DB, use SQL helpers. read the documents, section "SQL helpers". this example is just for your example.