我对 Flutter
FutureBuilder
的概念相当陌生,并且正在努力理解为什么代码片段中的 FutureBuilder<List<explore>>
可能为空,我该如何处理这种情况?
使用片段:
class Explore extends StatelessWidget {
const Explore({super.key});
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Explore>>(
future: FirestoreService().getExplore(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const LoadingScreen();
} else if (snapshot.hasError) {
return Center(
child: ErrorMessage(message: snapshot.error.toString()));
} else if (snapshot.hasData) {
var themes = snapshot.data!;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepPurpleAccent.shade700,
title: const Text('Explore'),
actions: [
IconButton(
icon: Icon(
FontAwesomeIcons.circleUser,
color: Colors.pink.shade200,
),
onPressed: () => Navigator.pushNamed(context, '/login'),
),
],
),
body: GridView.count(
primary: false,
padding: const EdgeInsets.all(20.0),
crossAxisSpacing: 10.0,
crossAxisCount: 2,
children: themes.map((topic) => Text(topic.)).toList(),
),
bottomNavigationBar: const BottomNavBar(),
);
} else {
return const Text('No themes found. Contact the developer.');
}
});
我定义 getExplore() 函数的 Firestore 代码片段:
class FirestoreService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
Future<List<Explore>> getExplore() async {
var ref = _db.collection('explore');
var snapshot = await ref.get();
var data = snapshot.docs.map((s) => s.data());
var themes = data.map((d) => Explore.fromJson(d));
return themes.toList();
}
}
我无法想出任何解决方案。
我认为首先小部件名称和型号名称不一样。 您可能面临这个问题。
对于上述问题,你只需更改
builder: (context, snapshot)
到
builder: (context, AsyncSnapshot<List<Explore>> snapshot)
您收到以下错误:
参数类型“Future
”无法分配给参数类型“Future
?”
因为代码中的
FutureBuilder
需要 nullable Future<List<Explore>>?
,请参阅问号作为其未来参数,但您的 getExplore()
函数返回 non-nullable Future<List<Explore>>
,没有问号。
要解决此问题,您应该确保
getExplore()
函数返回 nullable Future<List<Explore>>?
。请参阅下面如何修改 getExplore()
函数以返回 nullable future:
class FirestoreService {
Future<List<Explore>> getExplore() async {
try {
var ref = _db.collection('explore');
var snapshot = await ref.get();
var data = snapshot.docs.map((s) => s.data());
var themes = data.map((d) => Explore.fromJson(d));
return themes.toList();
} catch (e) {
print("Error fetching explore data: $e");
return null; //👈
}
}
}