👨‍💻
Flutter
  • 👨‍💻Flutter lessons
    • 🎨Flutter ui
      • 🚵‍♂️Travel app
        • 📱1. Lesson
        • 📱2.Lesson
      • 📚Books store
      • 🧑‍⚕️Doctor app
      • 🚖Taxi app
    • 🐦Основы Flutter
      • Page 1
      • Page 2
      • 🧑‍🏫Урок 1: Основные виджеты Flutter
        • Page
        • 🧩Container()
        • 🧩AppBar()
        • 🧩Text()
        • 🧩Icon()
        • 🧩Column()
        • 🧩Row()
        • 🧩TextButton()
        • 🧩ElevatedButton()
      • 🧑‍🏫Урок 2: Создаем UI
      • 🧑‍🏫Урок 3: Создаем UI
      • 🧑‍🏫Урок 4: Создаем UI
    • 🧩Основы dart
      • 🧑‍🏫01. Переменные часть 1
      • 🧑‍🏫01. Переменные часть 2
      • 🧑‍🏫02. Функции
      • 🧑‍🏫03. Условные операторы
      • 🧑‍🏫04. List
      • 🧑‍🏫05. Map
      • 🧑‍🏫06. Class
      • 🧑‍🏫07. Наследование
      • 🧑‍🏫08. Абстракция
      • 🧑‍🏫09. Интерфейсы
      • 🧑‍🏫10. Инкапсуляция
      • 🧑‍🏫11. Mixin
      • 🧑‍🏫12. Асинхронное программирование
      • 🧑‍🏫13. Streams
      • 🎯Final project
        • 🥦Grocery app
        • 🏠Home
    • ⚒️State management
      • ⬛Bloc
        • 1. Введение cubit
          • 1.1 Пример
          • 1.2 Пример
          • 1.3 Пример
          • 1.4 Пример
          • 1.5 Пример
        • 2. Введение в Bloc
      • 🌊Riverpod
    • 🏠Architechture
      • Clean Architechture
      • Bloc
    • 📲Locale storage
      • 🐝Hive
        • 🐝Ui
        • 🐝Hive - локальное хранилище: Введение
        • 🐝Hive - task app: часть 1
        • 🐝Hive - task app: часть 2
        • 🐝Hive - task app: часть 3
        • 🐝Hive - task app: часть 4
        • 🐝Hive - task app: часть 5
      • 🟩Sql
    • 📡Server
      • 📡Server - Lesson01 introduction
      • 📡Server - Lesson02 get data
      • 📡Server - Lesson03 News App get data
    • 🖥️Готовый backend
      • Firebase
      • Supabase
  • 🎯Dart practise
    • 🧑‍💻Переменные
      • 🧑‍💻String
      • 🧑‍💻int
      • 🧑‍💻double
      • 🧑‍💻bool
    • 🧑‍💻Функции
      • 🧑‍💻Обычные функции
      • 🧑‍💻Порядковые параметры
      • 🧑‍💻Обязательные параметры
      • 🧑‍💻Параметры по умолчанию
      • 🧑‍💻Функции-стрелки
      • 🧑‍💻Возвращаемые функции
    • 🧑‍💻Условные операторы
      • 🧑‍💻if/else
      • 🧑‍💻switch/case
      • 🧑‍💻тернарный оператор
    • 🧑‍💻Структура данных
      • 🧑‍💻List
      • 🧑‍💻Map
      • 🧑‍💻Set
    • 🧑‍💻ООП
  • 🧩Flutter Widgets
    • 💻Все виджеты
    • 🎞️Анимации
      • 🧩AnimatedContainer
      • 🧩AnimatedOpacity
      • 🧩AnimatedAlign
      • 🧩AnimatedCrossFade
      • 🧩Hero
      • 🧩AnimatedBuilder
      • 🧩AnimatedPositioned
      • 🧩AnimatedSwitcher
    • 🏗️Манипуляция пространством
      • 🧩Padding
      • 🧩SizedBox
      • 🧩Align
      • 🧩Center
      • 🧩Expanded
      • 🧩Flexible
      • 🧩Spacer
      • 🧩Column
      • 🧩Stack
      • 🧩Row
    • ✍️Отображение текста
      • 🧩RichText
      • 🧩FittedBox
      • 🧩SelectableText
      • 🧩Text
    • 📸Отображение изображений
      • 🧩Image()
      • 🧩Image.network
      • 🧩Image.asset
      • 🧩Image.file
      • 🧩Image.memory
      • 🧩FadeInImage
      • 🧩NetworkImage
      • 🧩AssetImage
    • 📃Списки и прокрутка
      • 🧩ListView()
      • 🧩ListView.builder()
      • 🧩GridView()
      • 🧩GridView.builder()
      • 🧩PageView()
      • 🧩SingleChildScrollView
      • 🧩CustomScrollView
      • 🧩ReorderableListView
      • 🧩NestedScrollView
    • ⌨️Кнопки
      • 🧩TextButton()
      • 🧩ElevatedButton()
      • 🧩IconButton()
      • 🧩DropDownButton()
      • 🧩FloatingActionButton
      • 🧩Checkbox
      • 🧩Radio
      • 🧩Switch
      • 🧩Slider
    • 📝Формы и ввод данных
      • 🧩TextField()
      • 🧩TextFormField
      • 🧩Form
      • 🧩FormField
      • 🧩DatePicker
      • 🧩TimePicker
    • 🧑‍🏫Диалоги и всплывающие окна
      • 🧩AlertDialog
      • 🧩SimpleDialog
      • 🧩BottomSheet
      • 🧩ExpansionPanel
      • 🧩SnackBar
      • 🧩PopupMenuButton
      • 🧩Tooltip
      • 🧩Dialog
    • 🛣️Навигация
      • 🧩BottomNavigationBar()
      • 🧩Navigator
      • 🧩Drawer
      • 🧩TabBar
    • 📱Отображение на экране
      • 🧩Scaffold
      • 🧩Container()
      • 🧩AppBar()
      • 🧩Icon()
      • 🧩Stepper()
  • 🎮Flutter Flame
    • Введение в разработку игр
  • 🔬Flutter projects
  • 🧑‍🎓Homeworks for everyday
    • 🧑‍🎓0. Переменные
    • 🧑‍🎓1. Функции - 1
    • 🧑‍🎓2. Функции - 2
    • 🧑‍🎓3. Условные операторы
    • 🧑‍🎓4. List
    • 🧑‍🎓5. Map
    • 🧑‍🎓6. class
    • 🐝Hive -
    • 🐝Hive clean architecture
    • 📡HTTP
    • 📡HTTP clean architecture
    • 💾Firebase
    • 💾Firebase clean architecture
Powered by GitBook
On this page
  1. Flutter lessons
  2. Server

Server - Lesson03 News App get data

PreviousServer - Lesson02 get dataNextГотовый backend

Last updated 1 year ago

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

  1. Ссылка newsApi --

  2. Ссылка на пакет HTTP --

  3. Ссылка на github --

// 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(),
    );
  }
}
👨‍💻
📡
📡
https://newsapi.org/
https://pub.dev/packages/http
https://github.com/Inf1nityLab/server_api