👨‍💻
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 - Lesson02 get data

PreviousServer - Lesson01 introductionNextServer - Lesson03 News App get data

Last updated 1 year ago

  • Ссылка на Pub Dev -

  • Ссылка на jsonPlaceholder -

// file post_screen.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:server_data/get/post_model.dart';

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

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

class _MyHomePageState extends State<MyHomePage> {
  Future<List<Post>>? futurePosts;


  Future<List<Post>> fetchPosts() async {
    final response = await http.get(Uri.https('jsonplaceholder.typicode.com', 'posts'));

    if (response.statusCode == 200) {
      final List<dynamic> data = jsonDecode(response.body);
      return data.map((item) => Post.fromJson(item)).toList();
    } else {
      throw Exception('Failed to load posts');
    }
  }

  @override
  void initState() {
    super.initState();
    futurePosts = fetchPosts();
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Posts'),
      ),
      body: Center(
        child: FutureBuilder<List<Post>>(
          future: futurePosts,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return ListView.builder(
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) {
                  final post = snapshot.data![index];
                  return Container(
                    height: 200,
                    color: Colors.tealAccent,
                    margin: const EdgeInsets.all(20),
                    child: ListTile(
                      title: Text('$index - title: ${post.title}'),
                      subtitle: Text('body: ${post.body}'),
                    ),
                  );
                },
              );
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }

            // Display a loading indicator while waiting for data
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}
// post_model.dart

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({required this.userId, required this.id, required this.title, required this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}
// main.dart
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 MyHomePage(),
    );
  }
}

👨‍💻
📡
📡
https://pub.dev/
https://jsonplaceholder.typicode.com/