首页 > 解决方案 > 使用 sqflite 颤振收藏或收藏元素

问题描述

我有一类像下面这样的词:

    class NewWords {

  final String name;
  final String definition;
  bool favorite;

  NewWords(
      {this.name,this.fav});
}

一切正常,数据已写入我的数据库表,但每次导航到滑块页面时,我都找不到保存 IconButton 状态以显示为已保存/已添加书签的方法。

我得到了这个 CarouselSlider() 小部件/库,其中包含以下文字:

Scaffold(
      body: CarouselSlider(
        options: CarouselOptions(
            scrollPhysics: BouncingScrollPhysics(),
            height: height,
            aspectRatio: 1,
            viewportFraction: 1.0,
            initialPage: 0,
            enlargeCenterPage: false,
            reverse: false,
            autoPlay: false,
            enableInfiniteScroll: false,
            scrollDirection: Axis.horizontal,
            onPageChanged: (index, reason) {
              if (!mounted) return;
              setState(() {
                _current = index;
              });
            }),
        items:<Widget>[
            //my slider Items are here
            sliderItem(),
            sliderItem(),
            sliderItem(),
        ].map((itm) => Builder(builder: (BuildContext context) {
          return Container(
            height: height,
            width: width,
            child: itm,
          );
        })).toList(),
      ),
    );

    // this is items function
    sliderItem(
      {String mainTerm,String definition}) {
    var height = MediaQuery.of(context).size.height;
    var width = MediaQuery.of(context).size.width;
    return ListView(
      children: <Widget>[
        Container(
          child: Card(
            child: Column(
              children: <Widget>[
                Padding(
                  padding:
                  EdgeInsets.only(left: width * 0.01, right: width * 0.02),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          IconButton(
                            padding: EdgeInsets.all(0),
                            onPressed: () {
                         
                            },
                            icon: Icon(Icons.keyboard_voice,
                                color: Colors.orange),
                          ),
                          Text(
                            "$mainTerm",
                            style: TextStyle(
                                fontFamily: "Raleway",
                                fontSize: 18.0,
                                fontWeight: FontWeight.w900,
                                color: Color(0xffa3bb7f)),
                          ),
                          SizedBox(
                            width: 8.0,
                          ),
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[widgetPhonetic],
                      ),
                    ],
                  ),
                ),
                sliderItemCards("$definition", "meaning:"),
                SizedBox(
                  height: height * 0.03,
                ),
                Padding(
                  padding: EdgeInsets.symmetric(
                      horizontal: width * 0.1, vertical: height * 0.03),
                  child: Card(
                    shape: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(15),
                      borderSide: BorderSide(color: Colors.transparent),
                    ),
                    elevation: 6,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        sliderItemIconButtons(Icon(Icons.video_library),
                                () { //somthing }),
                        Container(
                          color: Colors.black,
                          height: height * 0.04,
                          width: 2,
                        ),
                        sliderItemIconButtons(
                            newWordsList.firstSeasonWordsList[_current]
                                .favorite
                                ? Icon(Icons.bookmark)
                                : Icon(Icons.bookmark_border), () {
                          setState(() {
                            if (newWordsList
                                    .firstSeasonWordsList[_current].favorite) {
                              setState(() {
                                newWordsList.firstSeasonWordsList[_current]
                                    .favorite = false;
                                _delete(newWordsList.firstSeasonWordsList[_current].name);
                              });
                            } else if (newWordsList
                                    .firstSeasonWordsList[_current]
                                    .favorite ==
                                    false) {
                              setState(() {
                                newWordsList.firstSeasonWordsList[_current]
                                    .favorite = true;
                                _insert(
                                    newWordsList
                                        .firstSeasonWordsList[_current]
                                        .name,
                                    newWordsList
                                        .firstSeasonWordsList[_current]
                                        .definition);
                              });
                            }
                          });
                        }),
                      ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

sliderItemCards(String definition, String title) {
    return Card(
      elevation: 0,
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 10.0),
        child: Directionality(
          textDirection: TextDirection.rtl,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text(
                "$title",
                style: styleFarsi,
                textAlign: TextAlign.start,
              ),
              Container(
                child: Text(
                  "$definition",
                  style: styleFarsi,
                  textAlign: TextAlign.end,
                ),
                width: width * 0.6,
                padding: EdgeInsets.symmetric(vertical: 10),
              ),
            ],
          ),
        ),
      ),
    );
  }

  sliderItemIconButtons(Icon icon, Function function) {
    return IconButton(
      icon: icon,
      onPressed: function,
    );
  }

这些是我用来插入和删除的方法:

void _insert(String word, String meaning) async {
    // row to insert
    Map<String, dynamic> row = {
      DatabaseHelper.columnWord: '$word',
      DatabaseHelper.columnMeaning: "$meaning"
    };
    final id = await dbHelper.insert(row);
    print('inserted row id: $id');
  }

  void _query() async {
    final allRows = await dbHelper.queryAllRows();
    print('query all rows:');
    allRows.forEach((row) => print(row));
  }
  void _delete(String name) async {
    // Assuming that the number of rows is the id for the last row.

    final rowsDeleted = await dbHelper.delete("$name");
    print('deleted $rowsDeleted row(s): row ');
  }

和 dbhelper 文件:

import 'dart:io';

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

class DatabaseHelper {
  static final _databaseName = "MyDatabase2.db";
  static final _databaseVersion = 1;

  static final table = 'words';

  static final columnId = '_id';
  static final columnWord = 'word';
  static final columnMeaning = 'meaning';

  // make this a singleton class
  DatabaseHelper._privateConstructor();
  static final DatabaseHelper instance = DatabaseHelper._privateConstructor();

  // only have a single app-wide reference to the database
  static Database _database;
  Future<Database> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion, onCreate: _onCreate);
  }

  // SQL code to create the database table
  Future _onCreate(Database db, int version) async {
    await db.execute('''
          CREATE TABLE $table (
            $columnId INTEGER PRIMARY KEY,
            $columnWord TEXT NOT NULL,
            $columnMeaning TEXT NOT NULL
          )
          ''');
  }

  // Helper methods

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(Map<String, dynamic> row) async {
    Database db = await instance.database;
    return await db.insert(table, row);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows() async {
    Database db = await instance.database;
    return await db.query(table);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<int> queryRowCount() async {
    Database db = await instance.database;
    return Sqflite.firstIntValue(
        await db.rawQuery('SELECT COUNT(*) FROM $table'));
  }

  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(Map<String, dynamic> row) async {
    Database db = await instance.database;
    int id = row[columnId];
    return await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(String name) async {
    Database db = await instance.database;
    return await db
        .delete(table, where: '$columnWord = ?', whereArgs: ["$name"]);
  }
}

如果您能帮助我,我将不胜感激...

标签: flutterdartsqflite

解决方案


推荐阅读