Flutter change favorite button icon SQFlite if saved

114 Views Asked by At

I added save and remove method to onPressed of trailing IconButton but I have a problem: I can't change icon from favorite_border to favorite. I would be grateful If you could help!

search page

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",
  };

  String searchQuery = '';
  List<MapEntry<String, String>> filteredEntries = [];
  int currentIndex = 0;

  @override
  void initState() {
    super.initState();
    filteredEntries = myMap.entries.toList();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        color: Colors.greenAccent[700],
        home: Scaffold(
          appBar: AppBar(
              titleSpacing: 3,
              backgroundColor: Colors.greenAccent[700],
              title: _search()),
        body: FutureBuilder(
          future: _nothing(),
          builder: (context, data) {
            return 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),
                        ),
                      ],
                    ),
                  ),
                  trailing:
                  IconButton(
                    onPressed: () async {
                      List<Map<String, dynamic>> isFavourite =
                      await DatabaseHelper.instance.checkF(key);

                      if (isFavourite.length != 0) {
                        DatabaseHelper.instance.remove(key);
                      } else {
                        DatabaseHelper.instance
                            .add(ReadyDict(word: key, description: value));}
                    },
                    icon: Icon(), color: Colors.red,
                  ),
                  subtitle: RichText(
                    text: TextSpan(
                      children: [
                        TextSpan(
                          text: (value),
                          style: const TextStyle(
                            fontSize: 20,
                            color: Colors.black,
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }

  _search() {
    return TextField(
        decoration: const InputDecoration(
          contentPadding: EdgeInsets.all(5),
          filled: true,
          fillColor: Colors.white,
          hintText: 'enter',
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(
              Radius.circular(10.0),
            ),
          ),
        ),
        onSubmitted: (query) {
          _sout(query);
        });
  }

  _sout(query) {
    setState(
      () {
        searchQuery = query;
        filteredEntries = myMap.entries
            .where((entry) =>
                entry.key.contains(searchQuery) ||
                entry.value.contains(searchQuery))
            .toList();
      },
    );
  }

  _nothing(){}
}

and sqflite 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>>> checkF(String word) async {
    final db = await instance.database;
    return db.rawQuery('SELECT * FROM words WHERE word = "$word"');
  }

}

I tried to place isFavourite from onPressed after itembuilder but that didnt work cause when I wrote await it asked async but if add it a strange error appears. And how I understood you can't change icon from onPressed. I know there is methods with setState butit changed all icons not the saved one.

Thank you for ur help!!!

0

There are 0 best solutions below