Day 04 Day 4

Day 4

Day 4

~1 hour Intermediate Hands-on Precision AI Academy

Today's Objective

By the end of this lesson you will understand http and json deeply enough to apply it immediately in real projects.

bash.txt
BASH
flutter pub add http
dart.txt
DART
// lib/models/post.dart
class Post {
  final int id;
  final String title;
  final String body;

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

  factory Post.fromJson(Map<String, dynamic> json) => Post(
    id: json['id'] as int,
    title: json['title'] as String,
    body: json['body'] as String,
  );
}
dart.txt
DART
// lib/screens/posts_screen.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class PostsScreen extends StatefulWidget {
  const PostsScreen({super.key});
  @override State<PostsScreen> createState() => _PostsScreenState();
}

class _PostsScreenState extends State<PostsScreen> {
  late Future<List<Post>> _posts;

  Future<List<Post>> _fetchPosts() async {
    final res = await http.get(
      Uri.parse('https://jsonplaceholder.typicode.com/posts?_limit=20'));
    if (res.statusCode != 200) throw Exception('Failed to load');
    final List data = jsonDecode(res.body);
    return data.map((j) => Post.fromJson(j)).toList();
  }

  @override
  void initState() { super.initState(); _posts = _fetchPosts(); }

  @override
  Widget build(BuildContext context) => Scaffold(
    appBar: AppBar(title: const Text('Posts')),
    body: FutureBuilder<List<Post>>(
      future: _posts,
      builder: (ctx, snap) {
        if (snap.connectionState == ConnectionState.waiting)
          return const Center(child: CircularProgressIndicator());
        if (snap.hasError)
          return Center(child: Text('Error: ${snap.error}'));
        return RefreshIndicator(
          onRefresh: () async { setState(() => _posts = _fetchPosts()); },
          child: ListView.builder(
            itemCount: snap.data!.length,
            itemBuilder: (_, i) => ListTile(
              title: Text(snap.data![i].title),
              subtitle: Text(snap.data![i].body, maxLines: 1,
                overflow: TextOverflow.ellipsis),
            ),
          ),
        );
      },
    ),
  );
}

Exercise: Build a Weather App

  1. Register for a free OpenWeather API key
  2. Create a WeatherService class with a fetchWeather method
  3. Parse the JSON response into a Weather model
  4. Display temp, city, and condition icon
  5. Add pull-to-refresh to reload current conditions

Day 4 Summary