2

I have a list of news that comes from the API on the screen. Output code for one card with news(I shortened the code and left only the necessary):

Widget customListTile(Article article, BuildContext context) {
final newsController = Get.put(FavoritesController());
  return InkWell(
    Container(
            child:Row(
              textDirection: TextDirection.ltr,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text(
                  article.source.name,
                  style: TextStyle(
                    color: Colors.white,
                    backgroundColor: Colors.red,
                  ),
                ),
                IconButton(
                    onPressed: () {
                      newsController.addNews(article);
                    },
                    icon: const Icon(Icons.favorite_border)),
              ]
            )
          ),
  );
}

There is an icon, when clicked, the addNews() function is called.And there is a controller code where there is this function:

class FavoritesController extends GetxController {

  var _news = {}.obs;

  void addNews(Article article) {
   if(_news.containsKey(article)) {
      
     }
  }

  get news => _news;
}

I need when clicking on the icon, the news was added to a separate Saved page. How to write a function for adding news in a controller? And did I write the code correctly? Can you please tell me how this can be implemented?

userName
  • 903
  • 2
  • 20

1 Answers1

1

First of all, you either use

.obs

or

GetxController function update()

There is no need to change your code tho because this will work as well but you're not using GetxController correctly in this case.

Let's focus on the .obs

Move the

Now, make a ListView that is wrapped with Obx(() => ...) which uses the news obs.

Obx(() {
  return ListView(
    children: Get.find<FavoritesController>().news.map((e) => customListTile(e)).toList(),
  );
});

Let's move to the addNews function.

When you add an article use the update function.

 if(_news.containsKey(article)) {
   _news.update((e) => e[key]=value);
 }

Also, move

final newsController = Get.put(FavoritesController());

outside of this function, even though is not necessary, it makes no sense for it to be there.

Codrut Erdei
  • 104
  • 1
  • 6