Menu
CoddyTech

Un costruttore fromJson

Fa parte della sezione Dati e rete del percorso Flutter di Coddy. Lezione 17 di 27.

Leggere user['name'] as String in tutte le schermate diventa complicato, e un errore di battitura in una chiave causa un malfunzionamento. La soluzione abituale è creare una classe per i dati, con un costruttore che conosce il JSON. Si chiama fromJson:

class User {
  User({required this.name, required this.age});

  final String name;
  final int age;

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

User.fromJson è un costruttore con nome, un secondo modo per creare un User. La parola factory permette a un costruttore di eseguire codice e di return l'oggetto che crea. Un costruttore normale non può return nulla.

Ora il JSON viene letto in un unico punto. Il resto dell'app riceve un vero User, in cui user.name è una String e un errore di battitura causa un errore di compilazione invece di un null:

final body = await fetch('/user');
return User.fromJson(jsonDecode(body));

Quasi tutte le app che comunicano con un server hanno un fromJson per ogni tipo di dato che ricevono.

challenge icon

Sfida

Difficile

Il profilo mostra Unknown: loadUser ignora il JSON. Aggiungi a User una factory User.fromJson(Map<String, dynamic> json) che legga name, email e age, e fai in modo che loadUser restituisca User.fromJson(jsonDecode(body)). Importa dart:convert.

Provalo tu

import 'package:flutter/material.dart';

import 'api.dart';

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

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

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

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

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  late Future<User> _user;

  @override
  void initState() {
    super.initState();
    _user = loadUser();
  }

  Future<User> loadUser() async {
    final body = await fetch('/user');
    print(body);
    return User(name: 'Unknown', email: 'unknown', age: 0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Profile')),
      body: Center(
        child: FutureBuilder<User>(
          future: _user,
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Text('Could not load: ${snapshot.error}');
            }
            if (snapshot.hasData) {
              final user = snapshot.data!;
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    user.name,
                    style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 8),
                  Text(user.email, style: const TextStyle(fontSize: 18)),
                  const SizedBox(height: 8),
                  Text('${user.age} years old'),
                ],
              );
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

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

  final String name;
  final String email;
  final int age;
}
quiz iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Dati e rete

Esercitati da solo: Compilatore Flutter online