Flutter使用SQLITE添加喜爱的功能

brtdzjyr  于 2023-01-17  发布在  SQLite
关注(0)|答案(1)|浏览(158)

你好flutterMaven我正在从API获取数据,并显示在我的应用程序中的列表视图,当用户点击任何项目从列表视图其保存的数据在sqlite现在我想如果API数据已经存在于sqlite,然后我的拖尾星星图标变成黄色,否则它将保持不变,请检查我的代码,让我知道我可以实现这种类型的功能移动的应用程序。

import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:sqflite/sqflite.dart';
    import 'package:testfproject/Model/Articlemodel.dart';
    import 'package:testfproject/Model/Favourite/Favouritemodel.dart';
    import 'package:testfproject/Services/services.dart';
    import 'package:http/http.dart' as http;
    
    import '../Db/Databasehelper.dart';
    
    class Home extends StatefulWidget {
    
      @override
      State<Home> createState() => _HomeState();
    }
    
    class _HomeState extends State<Home> {
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
    
       // article();
      }
      Services api=Services();
      Databasehelper databasehelper=Databasehelper();
    
    
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('New Articles'),
          ),
          body: Column(
            children: [
         FutureBuilder(
           future: api.Article(),
           builder: (BuildContext context, AsyncSnapshot<List<Articlemodel>> snapshot) {
             if(snapshot.hasData){
               List<Articlemodel>?articles=snapshot.data;
               return Expanded(
                 child: ListView.separated(
                     shrinkWrap: true,
                     itemCount:articles!.length,
                     itemBuilder: (conext,index){
                       
                       //this  list tile when user press on trailing icon it saved data in sqlite
                       return ListTile(
                         trailing: IconButton(
                         icon:Icon(Icons.star),
                           onPressed: () {
                        databasehelper.insert(Favouritemodel(author: articles[index].author.toString(), title:articles[index].title.toString()));
    
                           },
    
                         ),
    
                         title: Text(articles[index].title.toString()),
                         //subtitle: Text(articles[index].author.toString()),
                       );
                     }, separatorBuilder: (BuildContext context, int index) {
                       return Divider();
                 },),
               );
             }else{
              return Container(
                 child: Text('NO data'),
               );
             }
    
           },
    
         )
            ],
    
          ),
        );
      }

}

//my Api services class
import 'dart:convert';

import 'package:testfproject/Model/Articlemodel.dart';
import 'package:http/http.dart' as http;

class Services{
  Future<List<Articlemodel>>Article() async {
    final response = await http.get(Uri.parse('https://newsapi.org/v2/top-headlines?country=us&apiKey=0fb3a9662c3747fba42ffd3d66cc612d'));
    if(response.statusCode==200){
      var data=jsonDecode(response.body.toString());
      final Iterable json = data["articles"];
      return json.map((article) => Articlemodel.fromJson(article)).toList();

    }else{
      throw Exception('Error');

    }

  }
}

model class of api


class Articlemodel {
  Source? source;
  String? author;
  String? title;
  String? description;
  String? url;
  String? urlToImage;
  String? publishedAt;
  String? content;
  bool? iSfavourite;

  Articlemodel(
      {this.source,
        this.author,
        this.title,
        this.description,
        this.url,
        this.urlToImage,
        this.publishedAt,
        this.content,
      });

  Articlemodel.fromJson(Map<String, dynamic> json) {
    source =
    json['source'] != null ? new Source.fromJson(json['source']) : null;
    author = json['author'];
    title = json['title'];
    description = json['description'];
    url = json['url'];
    urlToImage = json['urlToImage'];
    publishedAt = json['publishedAt'];
    content = json['content'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    if (this.source != null) {
      data['source'] = this.source!.toJson();
    }
    data['author'] = this.author;
    data['title'] = this.title;
    data['description'] = this.description;
    data['url'] = this.url;
    data['urlToImage'] = this.urlToImage;
    data['publishedAt'] = this.publishedAt;
    data['content'] = this.content;
    return data;
  }
}

class Source {
  String? id;
  String? name;

  Source({this.id, this.name});

  Source.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    return data;
  }
  }
//model class of sqlite for favouriting

class Favouritemodel {Favouritemodel(

    {required  this.author,required  this.title,}

    );

  Favouritemodel.fromJson(dynamic json) {

    author = json['author'];
    title = json['title'];

  }

  String? author;
  String? title;

  Map<String, dynamic> toJson() {
    final map = <String, dynamic>{};

    map['author'] = author;
    map['title'] = title;

    return map;
  }

}
//database helper class

import 'dart:io' as io;
import 'package:flutter/cupertino.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';

import '../Model/Favourite/Favouritemodel.dart';

class Databasehelper{
  static Database? _db;
   bool check=false;

  Future<Database?> get db async {
    if(_db != null)
      return _db;
    _db = await initDb();
    return _db;
  }

  //Creating a database with name test.dn in your directory
  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "favourite.db");
    var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return theDb;
  }

  // Creating a table
  void _onCreate(Database db, int version) async {
    // When creating the db, create the table
    await db.execute(
        "CREATE TABLE favourite(ID INTEGER PRIMARY KEY AUTOINCREMENT, author TEXT, title  TEXT  unique )");
    print("Created tables");
  }
  //insert data
  Future<Favouritemodel> insert(Favouritemodel favouritemodel) async {

    Database? db = await this.db;
    await db!.insert('favourite', favouritemodel.toJson()).catchError((e)=>(debugPrint(e)));

   return favouritemodel;
  }
p4rjhz4m

p4rjhz4m1#

首先将此函数添加到数据库帮助器中

Future<List<Favouritemodel>> favourites() async {
  Database? db = await this.db;

  final List<Map> data = await db!.query('favourite');

  return data.map((e) => Favouritemodel.fromJson(e)).toList();
}

并覆盖Favouritemodel中的等于运算符

@override
  bool operator ==(Object other) {
    return identical(this, other) ||
        (other is Favouritemodel &&
            author == other.author &&
            title == other.title);

接收构建方法中的收藏列表:

@override
Widget build(BuildContext context) {
  final futureFavourites = databasehelper.favourites();
  return Scaffold(
    // ...

最后将itemBuilder更改为:

itemBuilder: (conext, index) {
  return FutureBuilder<List<Favouritemodel>>(
    future: futureFavourites,
    builder: (context, favouriteSnapshot) {
      if(!favouriteSnapshot.hasData) {
        return ListTile(title: Text('Loading...'));
      }
      final favourites = favouriteSnapshot.data!;
      final favouriteModel = Favouritemodel(author: articles[index].author.toString(),
                               title:articles[index].title.toString());
      
      final isFavourite = favourites.contains(favouriteModel);
      return ListTile(
        trailing: IconButton(
          icon:Icon(Icons.star, color: isFavourite ? Colors.yellow : null),
          onPressed: () {
              databasehelper.insert(favouriteModel);
          },
        ),
        title: Text(articles[index].title.toString()),
        //subtitle: Text(articles[index].author.toString()),
      );
    }
  );
}

相关问题