Menu
CoddyTech

JSON-Werte und as

Teil des Abschnitts Daten und Netzwerk der Flutter-Journey von Coddy. Lektion 16 von 27.

Ein Wert aus einer JSON-Zuordnung ist dynamic. Dart weiß nicht, was es ist, deshalb prüft Dart nicht, was du damit machst, und der Editor kann dir nicht helfen. Du weißt, was der Server sendet: age ist eine Zahl, isPro ist true oder false. Gib das mit as an:

final age = user['age'] as int;
final isPro = user['isPro'] as bool;

as prüft den Wert genau an dieser Stelle. Von da an ist age ein int und isPro ein bool, und Dart behandelt sie entsprechend. Wenn der Server etwas anderes gesendet hat, schlägt die App in dieser Zeile mit einer Meldung fehl, die beide Typen nennt, statt irgendwo weit entfernt.

JSON-Werte entsprechen folgenden Dart-Typen: Text in Anführungszeichen ist ein String, eine ganze Zahl ist ein int, eine Zahl mit Dezimalpunkt ist ein double und true oder false ist ein bool. Beachte, dass true keine Anführungszeichen hat: Es ist ein bool, nicht der Text 'true'.

challenge icon

Aufgabe

Mittel

Zeige mehr vom Profil. Lies im Builder jeden Wert mit as aus: name und email als String, age als int, isPro als bool. Füge dann unter der E-Mail-Adresse Folgendes hinzu:

  • 28 years old, erstellt aus age
  • Pro member, wenn isPro wahr ist, und Free plan, wenn nicht

Probier es selbst

import 'dart:convert';

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<Map<String, dynamic>> _user;

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

  Future<Map<String, dynamic>> loadUser() async {
    final body = await fetch('/user');
    return jsonDecode(body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Profile')),
      body: Center(
        child: FutureBuilder<Map<String, dynamic>>(
          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)),
                ],
              );
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}
quiz iconTeste dich selbst

Diese Lektion enthält ein kurzes Quiz. Starte die Lektion, um es zu beantworten und deinen Fortschritt zu speichern.

Alle Lektionen in Daten und Netzwerk

Übe selbstständig: Online-Flutter-Compiler