Home > Software engineering >  How to create add to favorites functionality in Flutter?
How to create add to favorites functionality in Flutter?

Time:04-01

Beginner Flutter Developer. Implemented an application that lists news using newsapi.org. I need to implement the functionality of adding news to favorites using the Firebase database. When user clicks on the button, the news is added to favorites, and this must be implemented using the Firebase database. How can i do this?Now my news is simply displayed on the screen through the API, do I need to somehow enter them into the database for such functionality? Please tell me how to do it right. I will be grateful for help). below is the code of the main page where the news is displayed

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  ApiService client = ApiService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('News App', style: TextStyle(color: Colors.black)),
          backgroundColor: Color(0xfff27935),
          actions: [
            IconButton(
                onPressed: () {
                  showSearch(context: context, delegate: SearchNews());
                },
                icon: const Icon(Icons.search))
          ]),
      body: FutureBuilder(
        future: client.getArticle(),
        builder: (BuildContext context, AsyncSnapshot<List<Article>> snapshot) {
          if (snapshot.hasData) {
            List<Article>? articles = snapshot.data;
            return ListView.builder(
              itemCount: articles?.length,
              itemBuilder: (context, index) =>
                  customListTile(articles![index], context),
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      ),
    );
  }
}

import 'source_model.dart';

class Article {
  Source source;
  String author;
  String title;
  String description;
  String url;
  String urlToImage;
  String publishedAt;
  String content;

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

  factory Article.fromJson(Map<String, dynamic> json) {
    return Article(
      source: Source.fromJson(json['source']),
      author: json['author'] as String,
      title: json['title'] as String,
      description: json['description'] as String,
      url: json['url'] as String,
      urlToImage: json['urlToImage'] as String,
      publishedAt: json['publishedAt'] as String,
      content: json['content'] as String,
    );
  }
}

class Source {
  String id;
  String name;

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

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

CodePudding user response:

Depends on the API you're using. If it allows you to get a specific article by link at any time, you should rather store only the link and not the complete article. If however you can not access a specific article by link in the future, you will have to store the complete article if it is added to favourites.

CodePudding user response:

You can use shared_preferences package and every time user clicks on bookmark icon, call this function:

void addBookmark(id) async {
final prefs = await SharedPreferences.getInstance();
setState(() {
  bookmarkFromPrefs = (prefs.getString('bookmarkId') ?? "");
  if (bookmarkFromPrefs.contains(id)) {
    bookmarkFromPrefs = bookmarkFromPrefs.replaceFirst(id   ",", "");
    showBookmark = false;
  } else {
    bookmarkFromPrefs = bookmarkFromPrefs   id   ",";
    showBookmark = true;
  }

  prefs.setString("bookmarkId", bookmarkFromPrefs);
  log("Boomarks: "   bookmarkFromPrefs.toString());
});

}

Separate the bookmark button into a widget and call:

 void initState() {
    readBookmark();
    super.initState();
 }


void readBookmark() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      bookmarkFromPrefs = (prefs.getString('bookmarkId') ?? "");
    });
  }

Your separate bookmark widget should look like this:

InkWell(
  onTap: () {
    addBookmark(widget.guid);
  },
  child: Icon(
    bookmarkFromPrefs.contains(widget.guid)
        ? Icons.bookmark_rounded
        : Icons.bookmark_border_rounded,
    color: white,
  ),
);
  • Related