Home State in Flutter Apps The State Management Project

🏗️ The State Management Project — Build a Wikipedia Reader!

⏱️ 35-40 minutes 📊 Intermediate — New project! 📦 2 Projects included 🏷️ HTTP, API, JSON, Packages, Setup

🧒 A Brand New App! What Are We Building?

📚

Goodbye Birdle, Hello Wikipedia Reader!

You've mastered Flutter UI — now it's time to learn how apps talk to the internet! In this new topic, you'll build a completely new app: a Wikipedia Article Reader.

This app will:

  • 🌐 Fetch real data from the Wikipedia API
  • 📖 Display article summaries with titles, descriptions, and images
  • 🧠 Manage state properly with ChangeNotifier
  • 🏛️ Use the MVVM architecture pattern (Model-View-ViewModel)
🎯
Today you'll set up the foundation:
  • ✅ Create a brand new Flutter project
  • ✅ Add the http package for making web requests
  • ✅ Create a data model for Wikipedia articles
  • ✅ Set up the basic app structure
📦

What Are "Packages"? — Pre-Built Code From Other Developers

You could write all the code to make HTTP requests from scratch... but that would take hundreds of lines of complex networking code. Instead, you'll use a package — pre-written code shared by other developers!

📦

What is a Package?

A package is like a LEGO kit someone else already built. Instead of molding your own plastic bricks, you just grab their kit and snap it into your project.

🌐

The http Package

The http package lets you make web requests with simple functions like get() and post(). It handles all the complicated networking stuff for you!

🏪

pub.dev — The Package Store

Flutter's package repository is at pub.dev ↗. Thousands of free packages for everything from HTTP to animations to databases!

🗺️

The Road Ahead — 4 Lessons of Data & State

This lesson is the setup. Here's what's coming in the next lessons:

📋
  1. Today (Lesson 9): Set up the project, add packages, create data model
  2. Lesson 10: Make HTTP requests to fetch real Wikipedia data
  3. Lesson 11: Use ChangeNotifier to manage app state
  4. Lesson 12: Use ListenableBuilder to auto-update the UI when data changes

By the end of this topic, you'll understand professional state management — the same patterns used in real production apps!

1 Create a Brand New Flutter Project

We're starting fresh! Create a new project called wikipedia_reader — completely separate from your Birdle app.

Step 1.1 Run the Create Command

Open a terminal and run this command to create a minimal Flutter project:

Terminal — Create Wikipedia Reader Project
~ $ flutter create wikipedia_reader --empty
Creating project wikipedia_reader...
Resolving dependencies...
Wrote 13 files.

All done! You can now run your app with:
  cd wikipedia_reader
  flutter run -d chrome

This creates a new folder called wikipedia_reader with a minimal Flutter project inside. The --empty flag gives us a clean slate — no counter app boilerplate!

Step 1.2 Open the Project in VS Code

  1. Open VS Code
  2. Go to File → Open Folder
  3. Find and select the wikipedia_reader folder
  4. Click "Open"

You should see the familiar Flutter project structure in the file explorer: lib/main.dart, pubspec.yaml, etc.

2 Add the HTTP Package — Your App's Internet Connection

To fetch data from Wikipedia, your app needs to make HTTP requests — the same kind your web browser makes when you visit a website.

Step 2.1 Navigate to Your Project & Add the Package

In your terminal, navigate into the project folder and add the http package:

Terminal — Add http Package
~ $ cd wikipedia_reader
~/wikipedia_reader $ flutter pub add http
Resolving dependencies...
+ http 1.2.0
Downloading http 1.2.0...
Added http to pubspec.yaml

What just happened?

  1. flutter pub add http — Tells Flutter: "Add the http package to my project."
  2. Flutter updates your pubspec.yaml file, adding http: ^1.2.0 under dependencies.
  3. Flutter downloads the package code into your project so you can use it.
📄
Check it yourself! Open pubspec.yaml in VS Code. You'll see a new line under dependencies: that says http: ^1.2.0. This file is like a shopping list for your project — it tells Flutter which packages your app needs.

3 Create the Data Model — Teaching Flutter What Wikipedia Data Looks Like

When Wikipedia sends data, it arrives as JSON (a text format). We need a data model — Dart classes that know how to read JSON and turn it into something Flutter can use.

Step 3.1 Create the summary.dart File

  1. In VS Code, right-click on the lib folder
  2. Select "New File"
  3. Name it summary.dart
  4. Copy the entire code below and paste it into this file
  5. Save (Ctrl+S / Cmd+S)
📄 Click to expand — full summary.dart code (copy-paste this entire file)
lib/summary.dart
class Summary {
  Summary({required this.titles, required this.pageId, required this.extract, required this.extractHtml, required this.lang, required this.dir, required this.url, this.description, this.thumbnail, this.originalImage});
  final TitlesSet titles;
  final int pageId;
  final String extract, extractHtml, lang, dir, url;
  final String? description;
  final ImageFile? thumbnail, originalImage;
  bool get hasImage => originalImage != null && thumbnail != null;

  static Summary fromJson(Map<String, Object?> json) { /* JSON parsing logic */ }
}

class ImageFile {
  final String source;
  final int width, height;
  /* constructors, fromJson, toJson */
}

class TitlesSet {
  final String canonical, normalized, display;
  /* constructors, fromJson */
}

This file defines three classes that match the structure of Wikipedia's JSON data. You don't need to fully understand every line — the important part is the fromJson method, which converts raw JSON text into Dart objects.

Step 3.2 Understanding the Data Model — Plain English Version

Here's what each class represents in the real world:

📄

Summary

The main article info — title, first few sentences (extract), description, URL, and image.

🖼️

ImageFile

Information about one image — where it's located (source URL), its width, and its height.

📝

TitlesSet

Different versions of the title — the display version (for showing), canonical (for URLs), and normalized (for searching).

🧠
Key concept: The fromJson method is like a translator. Wikipedia sends data in JSON format (which looks like {"title": "Flutter", "pageid": 123}). The fromJson method reads that text and creates a proper Dart Summary object with typed properties. Without this translation, Flutter wouldn't know what to do with the raw JSON!

4 Update main.dart — The Starting Point

Now replace the default code in main.dart with our Wikipedia app's starting structure.

Step 4.1 Replace main.dart Content

Open lib/main.dart, delete everything, and paste this:

lib/main.dart
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart';     // ← NEW: http package

import 'summary.dart';                 // ← NEW: our data model

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

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

    @override
    Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                appBar: AppBar(
                    title: const Text('Wikipedia Flutter'),
                ),
                body: const Center(
                    child: Text('Loading...'),
                ),
            ),
        );
    }
}

What each import does:

  • dart:convert — Built-in Dart library for converting JSON (we'll use jsonDecode()).
  • dart:io — Built-in library for file/network operations.
  • package:flutter/material.dart — Flutter's Material Design widgets.
  • package:http/http.dartThe package we just added! Gives us get(), post(), and other HTTP functions.
  • summary.dartOur data model file. Imports the Summary, ImageFile, and TitlesSet classes.

5 Run Your App — Make Sure Everything Works

Before we move on, let's verify that the project is set up correctly.

Step 5.1 Launch the App

Terminal — Run the Wikipedia App
~/wikipedia_reader $ flutter run -d chrome
Launching lib/main.dart on Chrome...
Built build/web/...
Debug service listening...

You should see a simple app with:

  • An app bar at the top saying "Wikipedia Flutter"
  • The word "Loading..." centered on the screen
If you see "Wikipedia Flutter" and "Loading...", everything is working! The app doesn't do anything yet — it's just a placeholder. But the project structure, packages, and data model are all set up and ready for the next lesson where we'll actually fetch data!

📝 What You Learned Today

Created a New Project

Used flutter create wikipedia_reader --empty to start a fresh minimal Flutter app.

Added the http Package

Used flutter pub add http to install the HTTP package. Learned about pubspec.yaml and pub.dev.

Created a Data Model

Set up summary.dart with Summary, ImageFile, and TitlesSet classes — including fromJson for parsing Wikipedia API responses.

Set Up App Structure

Updated main.dart with all necessary imports and a basic scaffold with app bar and placeholder text.

🧠 Test Yourself!

Q1 What does the --empty flag do when running flutter create?

Q2 What command is used to add a package dependency to a Flutter project?

📦 Project 1: Explore pub.dev and Find 3 Interesting Packages

Project 1Beginner

Objective: Become Familiar with the Flutter Package Ecosystem

📋 Requirements:

  1. Go to pub.dev ↗
  2. Search for and find 3 packages that sound interesting to you
  3. For each package, note:
    • The package name
    • What it does (one sentence)
    • Its popularity score (shown on the package page)
  4. Try adding one of them to your project using flutter pub add [package_name] (don't worry if you don't use it — just practice the command!)

🎯 Goal:

Get comfortable browsing pub.dev and understanding that almost anything you want to do already has a package — you rarely need to build from scratch!

📦 Project 2: Create a Data Model for a Different API

Project 2Intermediate

Objective: Practice Creating Dart Data Classes

📋 Requirements:

  1. Create a new file lib/weather.dart
  2. Define a WeatherData class with these fields:
    • String cityName — the name of the city
    • double temperature — in Celsius
    • String condition — e.g., "sunny", "cloudy", "rainy"
    • int humidity — percentage (0-100)
  3. Add a fromJson factory method that creates a WeatherData from a JSON map
  4. Add a toString() method that returns something like: "London: 22°C, sunny (65% humidity)"
  5. In main.dart, create a test WeatherData object and print it

🎯 Expected Output:

A new Dart file with a properly structured data class that can parse JSON and display formatted weather information.

💡
Hint: Follow the same pattern as Summary.fromJson — use a constructor with named parameters, and a static factory method that reads from a Map.

🚀 What's Next?

Your Wikipedia Reader project is set up and ready! In the next lesson, you'll:

  • Make HTTP Requests — Actually fetch real data from Wikipedia!
  • Use the http.get() function to call the Wikipedia API
  • Parse real JSON responses into Summary objects
  • Display live Wikipedia article summaries on screen
Next Lesson: Make HTTP Requests →
🎉

Lesson Complete!

You've set up a brand new Flutter project with the http package and a Wikipedia data model. The foundation is ready — next, we'll make it come alive with real data!

Click the button above to track your progress!