【发布时间】:2021-12-15 03:21:36
【问题描述】:
我想将 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'],
);
}
}
【问题讨论】:
标签: json flutter dart listview