Skip to content

Commit

Permalink
Fixed Multiple bookmarks of single news article
Browse files Browse the repository at this point in the history
  • Loading branch information
insfirred committed Sep 9, 2022
1 parent 3de0a48 commit db968a2
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 65 deletions.
4 changes: 2 additions & 2 deletions lib/HomeScreen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ class HomeScreen extends StatefulWidget {
class _HomeScreenState extends State<HomeScreen> {
late PageController controller;

String url = "https://newsapi.org/v2/top-headlines?country=in&category=entertainment&apiKey=ff7aefdd16e6480faf2817f36e2daa5e";

late var jsonData;

String url = "https://newsapi.org/v2/top-headlines?country=in&category=entertainment&apiKey=ff7aefdd16e6480faf2817f36e2daa5e";

bool isNewsFetched = false;

void fetchNews() async{
Expand Down
7 changes: 5 additions & 2 deletions lib/Screens/bookmarks.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:inshorts_clone/Screens/newsList.dart';
import 'package:inshorts_clone/database/database.dart';
import 'package:sqflite/sqflite.dart';
import 'package:url_launcher/url_launcher.dart';
Expand All @@ -23,7 +24,7 @@ class _BookmarksState extends State<Bookmarks> {
isLoading = true;
});

this.list = await DatabaseClass.instance.read();
list = await DatabaseClass.instance.read();

setState(() {
isLoading = false;
Expand Down Expand Up @@ -52,7 +53,7 @@ class _BookmarksState extends State<Bookmarks> {
children: [
IconButton(
onPressed: () async{
int i = await DatabaseClass.instance.delete(list[newIndex]['_id']);
int i = await DatabaseClass.instance.delete(list[newIndex]['url']);
displayNews();
},
icon: const FaIcon(FontAwesomeIcons.trash)
Expand All @@ -61,6 +62,8 @@ class _BookmarksState extends State<Bookmarks> {
),
Text( list[newIndex]['title'] ,style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),),
SizedBox(height: 10,),
Text( list[newIndex]['_id'].toString() ,style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),),
SizedBox(height: 10,),
Text( list[newIndex]['_description'] ,style: TextStyle(color: Colors.grey[600], fontSize: 17),),
SizedBox(height: 10,),
Text( list[newIndex]['date'] ,style: TextStyle(color: Colors.grey, fontSize: 16,fontStyle: FontStyle.italic),),
Expand Down
98 changes: 52 additions & 46 deletions lib/Screens/newsList.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class _NewsListState extends State<NewsList>
with AutomaticKeepAliveClientMixin<NewsList> {
final DateTime now = DateTime.now();

final timeFormatter = DateFormat('Hms');
final timeFormatter = DateFormat('jm');

final dateFormatter = DateFormat('MMMMd');

Expand All @@ -48,10 +48,6 @@ class _NewsListState extends State<NewsList>
child: SizedBox(
height: MediaQuery.of(context).size.height / 3,
child: (widget.jsonData["articles"][index]["urlToImage"] != null)
// ? Image.network(
// "${widget.jsonData["articles"][index]["urlToImage"]}",
// fit: BoxFit.fill,
// )
? CachedNetworkImage(
imageUrl: "${widget.jsonData["articles"][index]["urlToImage"]}",
errorWidget: (context, url, error) => Icon(Icons.error),
Expand All @@ -61,6 +57,8 @@ class _NewsListState extends State<NewsList>
);
}

List<Map<String,dynamic>> list = [];

Widget NewsDetails(index) {

return Expanded(
Expand All @@ -73,52 +71,56 @@ class _NewsListState extends State<NewsList>
GestureDetector(
onTap: () async{
// Tapping on title
int i = await DatabaseClass.instance.create(
{
ColumnFields.title: widget.jsonData["articles"][index]["title"],
ColumnFields.description: (widget.jsonData["articles"][index]["content"] != null) ?widget.jsonData["articles"][index]["content"] :"",
ColumnFields.date: 'Published at: ${dateFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))} ${timeFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))}',
ColumnFields.url: (widget.jsonData["articles"][index]["url"] != null) ?widget.jsonData["articles"][index]["url"] :""

list = await DatabaseClass.instance.read();

bool isPresent = false;
for(int i=0 ; i<list.length; i++){
if(widget.jsonData["articles"][i]["url"] == widget.jsonData["articles"][index]["url"] ){
isPresent = true;
}
}

if(isPresent){
ScaffoldMessenger.of(context).showSnackBar(SnackBar(duration: Duration(milliseconds: 800),content: Text("Already present in Bookmarks")));
}
);
addedToBookmarks();
else{
int i = await DatabaseClass.instance.create(
{
ColumnFields.title: widget.jsonData["articles"][index]["title"],
ColumnFields.description: (widget.jsonData["articles"][index]["content"] != null) ?widget.jsonData["articles"][index]["content"] :"",
ColumnFields.date: 'Published at: ${dateFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))} ${timeFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))}',
ColumnFields.url: (widget.jsonData["articles"][index]["url"] != null) ?widget.jsonData["articles"][index]["url"] :""
}
);
addedToBookmarks();
}

},
child: Container(
child: Text(widget.jsonData["articles"][index]["title"],
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
child: Text(widget.jsonData["articles"][index]["title"],
style: const TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
),
),
SizedBox(height: 10),
const SizedBox(height: 10),

GestureDetector(
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
(widget.jsonData["articles"][index]["content"] != null)
? widget.jsonData["articles"][index]["content"]
: "",
style: TextStyle(color: Colors.grey[600], fontSize: 17),
textAlign: TextAlign.justify,
),
SizedBox(height: 15),
Text(
'Published at: ${dateFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))} ${timeFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))}',
style: TextStyle(color: Colors.grey, fontSize: 16,fontStyle: FontStyle.italic),
textAlign: TextAlign.justify,
),
SizedBox(
height: 20,
),
Text(
'swipe left for more info.',
style: TextStyle(color: Colors.grey, fontSize: 14),
textAlign: TextAlign.justify,
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
(widget.jsonData["articles"][index]["content"] != null)
? widget.jsonData["articles"][index]["content"]
: "",
style: TextStyle(color: Colors.grey[600], fontSize: 17),
textAlign: TextAlign.justify,
),
const SizedBox(height: 30),
Text(
'Published at: ${dateFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))} ${timeFormatter.format(DateTime.parse(widget.jsonData["articles"][index]["publishedAt"]))}',
style: const TextStyle(color: Colors.grey, fontSize: 14,fontStyle: FontStyle.italic),
textAlign: TextAlign.justify,
),
],
),
),
],
Expand All @@ -134,6 +136,8 @@ class _NewsListState extends State<NewsList>
addedToBookmarks();
},
);
print('hello');

}

@override
Expand All @@ -146,6 +150,8 @@ class _NewsListState extends State<NewsList>
scrollDirection: Axis.vertical,
itemCount: widget.jsonData["articles"].length,
itemBuilder: (context, index) {


return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expand Down
28 changes: 13 additions & 15 deletions lib/database/database.dart
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

class NewsModel{
final int? id;
final int id;
final String title;
final String description;
final String date;
final String url;

NewsModel({
this.id,
required this.id,
required this.title,
required this.description,
required this.date,
Expand All @@ -21,11 +19,11 @@ class NewsModel{

class ColumnFields{
// Column Field Names
static final String id = '_id';
static final String title = 'title';
static final String description = '_description';
static final String date = 'date';
static final String url = 'url';
static const String id = '_id';
static const String title = 'title';
static const String description = '_description';
static const String date = 'date';
static const String url = 'url';
}

class DatabaseClass{
Expand All @@ -35,9 +33,9 @@ class DatabaseClass{

static Database? _database;

static final _dbName = 'myDatabase.db';
static final _dbVersion = 1;
static final tableName = 'NewsTable';
static const _dbName = 'myDatabase.db';
static const _dbVersion = 1;
static const tableName = 'NewsTable';


Future<Database> get database async{
Expand All @@ -46,7 +44,7 @@ class DatabaseClass{
}

_database = await createDB(_dbName);
return _database!;
return _database!;
}

Future<Database> createDB(String dbName) async{
Expand Down Expand Up @@ -82,8 +80,8 @@ class DatabaseClass{
}

// Delete Operation
Future<int> delete(int id) async{
Future<int> delete(String url) async{
Database db = await instance.database;
return await db.delete(tableName,where: '${ColumnFields.id} = ?',whereArgs: [id]);
return await db.delete(tableName,where: '${ColumnFields.url} = ?',whereArgs: [url]);
}
}

0 comments on commit db968a2

Please sign in to comment.