我想將 api 資料顯示為串列并添加一個帶有 onTap 的 Inkwell,每次用戶單擊一個專案時,資料都會顯示在另一個類中,但是我在 main dart 的第 42 行出現錯誤
串列 resData = snapshot.data;
代碼只是加載但不顯示 api 中的任何內容。
我使用 api 專輯形式 flutter
主要的
import 'dart:async';
import 'package:flutter/material.dart';
import 'data/functions.dart';
import 'album.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Album> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
List resData = snapshot.data;
return ListView.builder(
itemCount: resData.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(title: Text(resData[index]["title"]),),
);
});
}
// if (snapshot.hasData) {
// return Text(snapshot.data!.title);
// } else if (snapshot.hasError) {
// return Text('${snapshot.error}');
// }
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
函式飛鏢
import 'dart:convert';
import 'package:gamess/album.dart';
import 'package:http/http.dart' as http;
Future<Album> fetchAlbum() async {
final response = await http
.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Album.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
專輯飛鏢
class Album {
final int userId;
final int id;
final String title;
Album({
required this.userId,
required this.id,
required this.title,
});
factory Album.fromJson(Map<String, dynamic> json) {
return Album(
userId: json['userId'],
id: json['id'],
title: json['title'],
);
}
}
uj5u.com熱心網友回復:
好的,首先您從 API 接收專輯串列,然后嘗試使用 fromJson 將專輯串列決議為單個專輯。要解決此問題,請將代碼更改functions.dart為此。
`
import 'dart:convert';
import '../album.dart';
import 'package:http/http.dart' as http;
Future<List<Album>> fetchAlbum() async {
final response =
await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
List<Album> albums = [];
List<dynamic> albumsJson = jsonDecode(response.body);
albumsJson.forEach(
(oneAlbum) {
Album album = Album.fromJson(oneAlbum);
albums.add(album);
},
);
return albums;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
`
第二件事是現在您正在正確接收資料,讓我們修復 ui,您不能在沒有 await 的情況下呼叫 Future,也不能在 init 上呼叫 await,因此洗掉了late Future<Album> futureAlbum;和futureAlbum = fetchAlbum();;
接下來,您必須適應未來構建器的未來呼叫,將 更改future: futureAlbum,為future: fetchAlbum(),;
現在您知道您正在接收一個串列,您必須在 Future 構建器上定義它。
有任何問題都可以問,main.dart檔案如下:
`
import 'package:flutter/material.dart';
import 'data/functions.dart';
import 'album.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<List<Album>>(
future: fetchAlbum(),
builder: (context, snapshot) {
if (snapshot.hasData) {
List<Album>? resData = snapshot.data;
return ListView.builder(
itemCount: resData != null ? resData.length : 0,
itemBuilder: (context, index) {
return Card(
child: ListTile(
title: Text(resData?[index].title ?? ""),
),
);
});
}
// if (snapshot.hasData) {
// return Text(snapshot.data!.title);
// } else if (snapshot.hasError) {
// return Text('${snapshot.error}');
// }
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
`
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/351716.html
