[The operator '[]' isn't defined for the type 'Album'.][1]
----------
[api code pasted here][2]
I am fetching data from internet using demo api and I want to show
that data in a list view builder but i am getting error because of
index in itembuilder please help me
gVKQ.png[2]: https://i.stack.imgur.com/KhQBY.png
应该可以。
由于您正在获取专辑列表,因此您应该依次返回并调整您的代码。
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.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) {
Iterable albums = jsonDecode(response.body);
return List<Album>.from(albums.map((album) => Album.fromJson(album)));
} else {
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'],
);
}
}
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<List<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<List<Album>>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext c, int index) {
return Text(snapshot.data![index].title!);
});
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
@override
Widget build(BuildContext context) {
CollectionReference users = FirebaseFirestore.instance.collection('users');
return FutureBuilder<DocumentSnapshot>(
future: users.doc(documentId).get(),
builder:
(BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.hasError) {
return Text("Something went wrong");
}
if (snapshot.hasData && !snapshot.data!.exists) {
return Text("Document does not exist");
}
if (snapshot.connectionState == ConnectionState.done) {
**Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;**
return Text("Full Name: ${data['full_name']} ${data['last_name']}");
}
return Text("loading");
},
);
}
一次性读取DocumentReference.get
if (snapshot.connectionState == ConnectionState.done) {
Map<String, dynamic> data = snapshot.data!.data() as Map<String, dynamic>;
return Text("Full Name: ${data['full_name']} ${data['last_name']}");
}
实时变化CollectionReference
&DocumentReference
return ListView(
children: snapshot.data!.docs.map((DocumentSnapshot document) {
Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
return ListTile(
title: Text(data['full_name']),
subtitle: Text(data['company']),
);
}).toList(),
);
博士
ExampleCollectionModel
class ExampleCollectionModel extends Equatable {
final String uid;
final String username;
final String email;
final String displayName;
final String avatarImageUrl;
final String bio;
const ExampleCollectionModel({
required this.uid,
required this.username,
required this.email,
required this.displayName,
required this.avatarImageUrl,
required this.bio,
});
static const ExampleCollectionModel empty = ExampleCollectionModel(
uid: '',
username: '',
email: '',
displayName: '',
avatarImageUrl: '',
bio: '',
);
ExampleCollectionModel copyWith({
String? uid,
String? username,
String? email,
String? displayName,
String? avatarImageUrl,
String? bio,
}) {
return ExampleCollectionModel(
uid: uid ?? this.uid,
username: username ?? this.username,
email: email ?? this.email,
displayName: displayName ?? this.displayName,
avatarImageUrl: avatarImageUrl ?? this.avatarImageUrl,
bio: bio ?? this.bio,
);
}
Map<String, dynamic> toMap() {
return {
'uid': uid,
'username': username,
'email': email,
'displayName': displayName,
'avatarImageUrl': avatarImageUrl,
'bio': bio,
};
}
Map<String, dynamic> toDocument() {
return {
'username': username,
'email': email,
'displayName': displayName,
'avatarImageUrl': avatarImageUrl,
'bio': bio,
};
}
factory ExampleCollectionModel.fromDocument(DocumentSnapshot doc) {
final data = doc.data() as Map<String, dynamic>;
print('fromDocment ${data}');
return ExampleCollectionModel(
uid: doc.id,
username: data['username'] ?? '',
email: data['email'] ?? '',
displayName: data['displayName'] ?? '',
avatarImageUrl: data['avatarImageUrl'] ?? '',
bio: data['bio'] ?? '',
);
}
**itemCount: snapshot.data!.title!长度! !> /div>