這是我的 json:https ://my-json-server.typicode.com/fluttirci/testJson/db
此代碼僅在只有一個 json 物件時才有效,但是,對于此員工 JSON,它不起作用。Flutter 檔案對此主題不是很清楚。它們只適用于一行 jsons。我想做的是,我想把所有的資料都放到我的手機螢屏上。如果我明白了,我會將它們顯示在表格或網格上。但它仍然行不通。它說型別 'Null' 不是型別 'int' 的子型別。這是我的代碼:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));
print(response);
Map<String, dynamic> userMap = jsonDecode(response.body);
if (response.statusCode == 200) {
return Album.fromJson(userMap); //testing
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album(this.userId, this.id, this.title);
Album.fromJson(Map<String, dynamic> json)
: userId = json['userId'],
id = json['id'],
title = json['title'];
Map<String, dynamic> toJson() => {
'userId': userId,
'id': id,
'title': title,
};
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
late Future<Album> user;
@override
void initState() {
super.initState();
user = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
),
);
}
}
uj5u.com熱心網友回復:
嘗試這個:
Future<List<Album>> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));
print(response);
Map<String, dynamic> userMap = jsonDecode(response.body);
if (response.statusCode == 200) {
return (userMap['employees'] as List).map((e) => Album.fromJson(e)).toList()
} else {
throw Exception('Failed to load album');
}
}
然后將您的 FutureBuilder 更改為:
FutureBuilder<List<Album>>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Album> data = snapshot.data ?? [];
return ListView.builder(
itemBuilder: (context, index) {
return Column(children: [
Text(data[index].title ?? ""),
]);
},
itemCount: data.length,
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
)
uj5u.com熱心網友回復:
您的 response.body 回傳一個employees鍵串列。并用回應測驗這個模型
Future<List<Album>?> fetchAlbum() async {
final response = await http.get(
Uri.parse('https://my-json-server.typicode.com/fluttirci/testJson/db'));
if (response.statusCode == 200) {
final data = jsonDecode(response.body)["employees"] as List?;
return data?.map((e) => Album.fromMap(e)).toList();
} else {
throw Exception('Failed to load album');
}
}
class Album {
final int userId;
final int id;
final String title;
Album(this.userId, this.id, this.title);
Map<String, dynamic> toMap() {
final result = <String, dynamic>{};
result.addAll({'userId': userId});
result.addAll({'id': id});
result.addAll({'title': title});
return result;
}
factory Album.fromMap(Map<String, dynamic> map) {
return Album(
map['userId']?.toInt() ?? 0,
map['id']?.toInt() ?? 0,
map['title'] ?? '',
);
}
String toJson() => json.encode(toMap());
factory Album.fromJson(String source) => Album.fromMap(json.decode(source));
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late final user = fetchAlbum();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: FutureBuilder<List<Album>?>(
future: user,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data?.length,
itemBuilder: (context, index) =>
Text("${snapshot.data?[index].title}"),
);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
),
),
);
}
}
uj5u.com熱心網友回復:
所以resultMap應該看起來像這樣:
{
"employees": [
{
"userId": 1,
"id": 2,
"title": "Doe"
},
{
"userId": 2,
"id": 3,
"title": "Smith"
},
{
"userId": 3,
"id": 4,
"title": "Jones"
}
]
}
這是一張只有一個屬性的地圖,它作為List其他地圖的一個屬性
所以訪問json['userId']將嘗試獲取userId從該地圖中獲取地圖中不存在的地圖
您需要訪問該employees屬性:
json["employees"]
然后你得到它的值,它是嵌套List的映射,現在你可以訪問List帶有索引的元素,然后得到userId:
json["employees"][0]["userId"] // 1
json["employees"][1]["userId"] // 2
json["employees"][2]["userId"] // 3
希望這能為您提供更好的方法來解決您正在嘗試做的事情以及您需要做的事情。
所以這 :
return Album.fromJson(userMap);
應該用這個代替,例如:
return Album.fromJson(userMap["employees"][0]);
這里userMap["employees"][0]是:
{
"userId": 1,
"id": 2,
"title": "Doe"
},
現在它應該從中制作一個Album物件。
如果要獲取 List 而不是 ,則需要使用方法或使用 aList<Map<string, dynamic>>遍歷整個串列mapfor loop
希望能幫助到你
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524558.html
標籤:扑镖
