Reputation: 11
I am new in flutter and I would be grateful for your help! Right now I am stuck on adding Favorite feature. The problem is that I need the color to change if it already exists in table. I have a ready map for search function and a table made using sqflite. I dont use futurebuilder due to that I cant use async/await. here is my page with search function
import 'package:flutter/material.dart';
import 'package:testshared/database/sql_helper.dart';
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
Map<String, String> myMap = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5",
"key6": "value1",
"key7": "value2",
"key8": "value3",
"key9": "value4",
"key10": "value5",
"key11": "value1",
"key12": "value2",
"key13": "value3",
"key14": "value4",
"key15": "value5",
};
List<MapEntry<String, String>> filteredEntries = [];
bool isExist = false;
@override
void initState() {
super.initState();
filteredEntries = myMap.entries.toList();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
color: Colors.greenAccent[700],
home: Scaffold(
appBar: AppBar(
titleSpacing: 3,
backgroundColor: Colors.greenAccent[700],
title: TextField(
decoration: const InputDecoration(
contentPadding: EdgeInsets.all(5),
filled: true,
fillColor: Colors.white,
hintText: 'Enter your word',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
),
),
),
onSubmitted: (query) {
setState(() {
filteredEntries = myMap.entries
.where((entry) =>
entry.key.contains(query) ||
entry.value.contains(query))
.toList();
});
},
),
),
body: Column(
children: [
Expanded(
child: ListView.builder (
itemCount: filteredEntries.length,
itemBuilder: (BuildContext context, int index) {
MapEntry<String, String> entry = filteredEntries[index];
String key = entry.key;
String value = entry.value;
return ListTile(
title: RichText(
text: TextSpan(
children: [
TextSpan(
text: (key),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
color: Colors.red),
),
],
),
),
subtitle: RichText(
text: TextSpan(
children: [
TextSpan(
text: (value),
style: const TextStyle(
fontSize: 20,
color: Colors.black,
),
),
],
),
),
trailing: IconButton(
onPressed: () {
DatabaseHelper.instance.add(
ReadyDict(word: entry.key, description: entry.value),
);
},
icon: const Icon(Icons.favorite_border),
color: Colors.red,
),
);
},
),
),
],
),
),
);
}
}
and my sqflite database page
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'dart:io';
class ReadyDict {
final int? id;
final String word;
final String description;
ReadyDict({this.id, required this.word, required this.description});
factory ReadyDict.fromMap(Map<String, dynamic> json) => ReadyDict(
id: json['id'],
word: json['word'],
description: json['description'],
);
Map<String, dynamic> toMap() {
return{
'word': word,
'description': description,
};
}
}
class DatabaseHelper {
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'words.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute("""
CREATE TABLE words(
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
word TEXT,
description TEXT
createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)""");
}
Future<List<ReadyDict>> getItems() async {
Database db = await instance.database;
var words = await db.query('words', orderBy: 'id DESC');
List<ReadyDict> wordsList = words.isNotEmpty
? words.map((c) => ReadyDict.fromMap(c)).toList()
: [];
return wordsList;
}
Future<int> add(ReadyDict readyDict) async {
Database db = await instance.database;
return await db.insert('words', readyDict.toMap());
}
Future<int> remove(String word) async {
Database db = await instance.database;
return await db.delete('words', where: 'word LIKE ?', whereArgs: ['%$word%']);
}
Future<List<Map<String, dynamic>>> getItem(String key) async {
Database db = await instance.database;
return db!.rawQuery('SELECT * FROM words WHERE word = "$key"');
}
static Future<List<Map<String, dynamic>>> checkFavourite(var key) async {
final Database db = await instance.database;
return db!.rawQuery('SELECT * FROM words WHERE word = "$key"');
}
}
I am new in stackoverflow too, so if I had some mistakes in my question I am sorry, Thank you!
I have tried to use checkFavourite function, it was in answer for another question, but that doesnt work cause when I call that with await it ask to be in async. Do i need to create another table with unsaved words and make a search field using textfield + dart.io to use futurebuilder? Thank you!
Upvotes: 0
Views: 403