📡Server - Lesson03 News App get data

Cкоро будет видео и картинка

  1. Ссылка newsApi -- https://newsapi.org/

  2. Ссылка на пакет HTTP -- https://pub.dev/packages/http

  3. Ссылка на github -- https://github.com/Inf1nityLab/server_api

// news_model.dart

class Article {

  final String title;
  final String description;
  final String urlToImage;
  final String url;

  Article({
    required this.title,
    required this.description,
    required this.urlToImage,
    required this.url,
  });

  factory Article.fromJson(Map<String, dynamic> json) {
    return Article(
      title: json['title'] ?? 'title',
      description: json['description'] ?? 'description',
      urlToImage: json['urlToImage'] ?? 'urlToImage',
      url: json['url'] ?? 'url',
    );
  }
}
// news_screen.dart

import 'package:flutter/material.dart';
import 'package:server_data/news/service.dart';
import 'news_model.dart';

class MyNewsApp extends StatefulWidget {
  const MyNewsApp({super.key});

  @override
  State<MyNewsApp> createState() => _MyNewsAppState();
}

class _MyNewsAppState extends State<MyNewsApp> {
  NewsApiService newsService = NewsApiService();
  List<Article>? articles;

  @override
  void initState() {
    super.initState();
    _getHeadlines();
  }

  Future<void> _getHeadlines() async {
    try {
      final fetchedArticles = await newsService.getHeadlines();
      setState(() {
        articles = fetchedArticles; // If using the model class
      });
    } catch (error) {
      print(error);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('My News App'),
      ),
      body: articles != null
          ? ListView.builder(
              itemCount: articles!.length, // If using the model class
              itemBuilder: (context, index) =>
                  _articleCard(articles![index]), // If using the model class
            )
          : const Center(
              child: CircularProgressIndicator(),
            ),
    );
  }

  Widget _articleCard(Article article) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Column(
        children: <Widget>[
          article.urlToImage.isNotEmpty
              ? Container(
                  height: 400,
                  width: double.infinity,
                  child: Image.network(
                    "https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg",
                  ),
                )
              : Container(
                  height: 200,
                  color: Colors.grey[200],
                  child: const Center(child: Text('No image available')),
                ),
          const SizedBox(height: 10),
          Text(
            article.title,
            style: const TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 5),
          Text(article.description),
          const SizedBox(height: 10),
        ],
      ),
    );
  }
}
// service.dart

import 'dart:convert';

import 'news_model.dart';
import 'package:http/http.dart' as http;


class NewsApiService {
  final String _apiKey = 'f0c8f55bea4b4dae96b5423c5a9ac993'; // Replace with your News API key
  final String _baseUrl = 'https://newsapi.org/v2/';

  Future<List<Article>> getHeadlines({String category = 'business'}) async {
    final Uri url = Uri.parse(_baseUrl + 'top-headlines?apiKey=$_apiKey&category=$category');
    final response = await http.get(url);

    if (response.statusCode == 200) {
      final jsonData = jsonDecode(response.body);
      final articles = jsonData['articles'] as List;

      // If using the model class:
      return articles.map((article) => Article.fromJson(article)).toList();

      // If not using the model class:
      // return articles.map((article) => article).toList();
    } else {
      throw Exception('Failed to load news');
    }
  }
}
// main.dart
import 'package:flutter/material.dart';
import 'package:server_data/news/news_screen.dart';


void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyNewsApp(),
    );
  }
}

Last updated