JSON Değerleri ve as
Coddy'nin Flutter Journey'sinin Veri ve Ağ bölümünün bir parçası. Ders 16 / 27.
Bir JSON haritasındaki değer dynamic türündedir. Dart bunun ne olduğunu bilmez; bu yüzden onunla ne yaptığını denetlemez ve düzenleyici de sana yardımcı olamaz. Sunucunun ne gönderdiğini biliyorsun: age bir sayıdır, isPro ise true veya false değeridir. Bunu as ile belirt:
final age = user['age'] as int;
final isPro = user['isPro'] as bool;as, değeri tam o noktada denetler. O andan itibaren age bir int, isPro ise bir bool olur ve Dart onlara bu şekilde davranır. Sunucu başka bir şey gönderdiyse uygulama, çok daha uzaktaki bir yerde değil, o satırda her iki türün de adını belirten bir mesajla hata verir.
JSON değerleri Dart türlerine şöyle karşılık gelir: Tırnak içindeki metin bir String, tam sayı bir int, noktalı bir sayı bir double, true veya false ise bir bool değeridir. true değerinin tırnak içinde olmadığına dikkat et: bu bir bool değeridir, 'true' metni değildir.
Görev
OrtaProfilin daha fazlasını göster. Oluşturucuda her değeri as ile oku: name ve email değerlerini String olarak, age değerini int olarak, isPro değerini bool olarak. Ardından e-postanın altına şunları ekle:
28 years old,agedeğerinden oluşturulurisProtrue olduğundaPro member, değilseFree plan
Kendin dene
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();
},
),
),
);
}
}
Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.
Veri ve Ağ bölümündeki tüm dersler
3Çağrılar Başarısız Olduğunda
try ile Hataları YakalamaHata Fırlatmafinally ile TemizlemeFutureBuilder Hata DurumuYeniden Dene DüğmesiKendi başına pratik yap: Online Flutter derleyicisi