How to convert JSON news data from API to flutter news blocks in flutter news toolkit

I am working with flutter news toolkit. I was able to successfully setup environment for it and everything is working fine as long as I am providing data from in memory data source. But when I want to get data from my own custom source then there is no way to transform that data into flutter news blocks.
Actually I want to server a rich content to my users. But I am not sure how can I achieve this with flutter news toolkit by converting my json into news blocks.

Create a Custom Data Model:

First, define a custom data model that represents your news data. This model should match the structure of your JSON data. You can use the json_serializable package to generate Dart code for JSON serialization/deserialization. Here’s an example:

import 'package:json_annotation/json_annotation.dart';

part 'news_model.g.dart';

@JsonSerializable()
class NewsModel {
  final String title;
  final String description;
  final String imageUrl;
  // Add other fields as needed

  NewsModel({
    required this.title,
    required this.description,
    required this.imageUrl,
  });

  factory NewsModel.fromJson(Map<String, dynamic> json) =>
      _$NewsModelFromJson(json);

  Map<String, dynamic> toJson() => _$NewsModelToJson(this);
}

Run flutter pub run build_runner build to generate the necessary serialization code based on your model.

Fetch and Parse JSON Data:

Use the http package or any other HTTP client to fetch your JSON data from your custom source. Then, parse the JSON data into a list of your custom data model objects:

Future<List<NewsModel>> fetchNewsData() async {
  final response = await http.get('your_api_endpoint');
  if (response.statusCode == 200) {
    final List<dynamic> jsonData = json.decode(response.body);
    final List<NewsModel> newsList =
        jsonData.map((data) => NewsModel.fromJson(data)).toList();
    return newsList;
  } else {
    throw Exception('Failed to load news data');
  }
}

Convert to Flutter News Blocks:

To display the news data using Flutter News Toolkit, you need to convert your custom data model objects into NewsBlock objects provided by the toolkit. You can do this by mapping your data:

List<NewsBlock> convertToNewsBlocks(List<NewsModel> newsData) {
  return newsData.map((newsItem) {
    return NewsBlock(
      title: newsItem.title,
      subtitle: newsItem.description,
      thumbnailUrl: newsItem.imageUrl,
      // Add other fields as needed
    );
  }).toList();
}

Display News Blocks in Flutter News Toolkit:

Finally, use the NewsProvider and NewsConsumer widgets from the Flutter News Toolkit to display your news data in your Flutter app:

NewsProvider(
  newsBlocks: convertToNewsBlocks(newsData),
  child: NewsConsumer(
    builder: (BuildContext context, List<NewsBlock> newsBlocks) {
      return ListView.builder(
        itemCount: newsBlocks.length,
        itemBuilder: (context, index) {
          return NewsTile(newsBlock: newsBlocks[index]);
        },
      );
    },
  ),
)

Replace NewsTile with your custom widget for displaying news articles.

By following these steps, you should be able to convert your JSON news data from your custom source into Flutter News Blocks and display them in your Flutter app using the Flutter News Toolkit. Make sure to adjust the code to match the structure of your JSON data and the requirements of your app.

Leave a Comment