0
0
Fluttermobile~20 mins

Model classes from JSON in Flutter - Mini App: Build & Ship

Choose your learning style9 modes available
Build: User Profile Screen
This screen shows user information loaded from a JSON string. You will create model classes to parse the JSON and display the user's name and email.
Target UI
-------------------------
|      User Profile      |
|-----------------------|
| Name:                 |
| Email:                |
|                       |
| [Refresh Data]        |
-------------------------
Create a Dart model class User with fields: name (String), email (String)
Add a factory constructor to parse User from JSON string
Display the user's name and email on the screen
Add a Refresh Data button that reloads the user data from the JSON
Starter Code
Flutter
import 'package:flutter/material.dart';
import 'dart:convert';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: UserProfileScreen(),
    );
  }
}

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

  @override
  State<UserProfileScreen> createState() => _UserProfileScreenState();
}

class _UserProfileScreenState extends State<UserProfileScreen> {
  late User user;

  @override
  void initState() {
    super.initState();
    // TODO: Initialize user from JSON
  }

  void _refreshUser() {
    setState(() {
      // TODO: Reload user from JSON
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('User Profile')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Name: '), // TODO: Show user name
            const SizedBox(height: 8),
            Text('Email: '), // TODO: Show user email
            const Spacer(),
            ElevatedButton(
              onPressed: _refreshUser,
              child: const Text('Refresh Data'),
            ),
          ],
        ),
      ),
    );
  }
}

// TODO: Create User model class with fromJson factory
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Flutter
import 'package:flutter/material.dart';
import 'dart:convert';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: UserProfileScreen(),
    );
  }
}

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

  @override
  State<UserProfileScreen> createState() => _UserProfileScreenState();
}

class _UserProfileScreenState extends State<UserProfileScreen> {
  late User user;

  final String userJson = '{"name": "Alice Johnson", "email": "alice@example.com"}';

  @override
  void initState() {
    super.initState();
    user = User.fromJson(jsonDecode(userJson));
  }

  void _refreshUser() {
    setState(() {
      user = User.fromJson(jsonDecode(userJson));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('User Profile')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Name: ${user.name}'),
            const SizedBox(height: 8),
            Text('Email: ${user.email}'),
            const Spacer(),
            ElevatedButton(
              onPressed: _refreshUser,
              child: const Text('Refresh Data'),
            ),
          ],
        ),
      ),
    );
  }
}

class User {
  final String name;
  final String email;

  User({required this.name, required this.email});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      name: json['name'] as String,
      email: json['email'] as String,
    );
  }
}

We created a User class with name and email fields. The fromJson factory constructor converts a JSON map into a User object.

In the stateful widget, we store the JSON string and parse it in initState to initialize the user. The _refreshUser method reloads the user data from the same JSON string and updates the UI.

The UI shows the user's name and email using string interpolation inside Text widgets. The Refresh Data button triggers the reload.

Final Result
Completed Screen
-------------------------
|      User Profile      |
|-----------------------|
| Name: Alice Johnson    |
| Email: alice@example.com|
|                       |
| [Refresh Data]        |
-------------------------
Tapping 'Refresh Data' reloads the user data from JSON and updates the displayed name and email.
Stretch Goal
Add error handling for invalid JSON data and show an error message on the screen.
💡 Hint
Use try-catch around jsonDecode and display a Text widget with error if parsing fails.