Flutter中snapshot参数不允许为null报错,加required后PostDetails仍报错如何解决?
问题根源
你遇到的报错是Flutter空安全机制的强制校验,同时代码存在多处逻辑冲突:
- PostDetails类构造函数重复定义snapshot参数:同时声明了位置参数
List<DocumentSnapshot<Object?>> snapshot和命名参数required this.snapshot,两个参数类型不匹配且逻辑冲突 - PostDetails的类成员变量
DocumentSnapshot snapshot未声明可空也未加late修饰,不符合空安全校验规则 - Home页传递参数时错误传递了整个snapshot列表,但是PostDetails实际需要的是单个
DocumentSnapshot对象 - PostDetails里定义的
get title => null会导致取值时出现空异常
修复步骤
第一步:修正PostDetails类代码
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; //ignore: must_be_immutable class PostDetails extends StatefulWidget { // 加late修饰,告知运行时变量会在使用前完成初始化 late DocumentSnapshot snapshot; // 删掉多余的位置参数,仅保留命名required参数传递单个snapshot PostDetails({required this.snapshot}); @override _PostDetailsState createState() => _PostDetailsState(); } class _PostDetailsState extends State<PostDetails> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Post Details"), backgroundColor: Colors.green, ), body: Card( elevation: 10.0, margin: const EdgeInsets.all(10.0), child: ListView( children: <Widget>[ Container( padding: const EdgeInsets.all(10.0), child: Row( children: <Widget>[ CircleAvatar( child: Text(widget.snapshot["title"][0]), backgroundColor: Colors.green, foregroundColor: Colors.white, ), const SizedBox( width: 10.0, ), Text( widget.snapshot["title"], style: const TextStyle(fontSize: 22.0, color: Colors.green), ), ], )), const SizedBox( height: 7.0, ), Container( margin: const EdgeInsets.all(1.0), child: Text( widget.snapshot["content"], style: const TextStyle(fontSize: 18.0), ), ) ], ), ), ); } }
第二步:修正Home页参数传递逻辑
class _HomeState extends State<Home> { late StreamSubscription<QuerySnapshot> subscription; late List<DocumentSnapshot> snapshot; // 新版cloud_firestore已废弃Firestore,替换为FirebaseFirestore CollectionReference collectionReference = FirebaseFirestore.instance.collection("Post"); Color gradientStart = Colors.deepPurple[700]!; Color gradientEnd = Colors.purple[500]!; passData(DocumentSnapshot snap) { Navigator.of(this.context).push(MaterialPageRoute( // 传递当前点击的单个snap对象,补充命名参数名 builder: (context) => PostDetails( snapshot: snap, ))); } }
内容的提问来源于stack exchange,提问作者zenx
相关产品推荐
相关产品推荐

