我想添加一个消息传递插件到我的应用程序,但我得到错误的"Null检查操作符用于空值"。我得到uid错误,'?我把它放在字符串旁边,但是它不工作。
错误:
类型
Null
不是类型'String'的子类型
截图
这是我的用户模型
user.dart
class User {
late final String username;
final String uid;
final String email;
late final String bio;
final List followers;
final List following;
late final String photoUrl;
User({
required this.email,
required this.uid,
required this.photoUrl,
required this.username,
required this.bio,
required this.followers,
required this.following,
});
get state => null;
Map<String, dynamic> toJson() => {
'username': username,
'uid': uid,
'email': email,
'photoUrl': photoUrl,
'bio': bio,
'followers': followers,
'following': following,
};
static User fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return User(
username: snapshot['username'],
uid: snapshot['uid'],
email: snapshot['email'],
photoUrl: snapshot['photoUrl'],
bio: snapshot['bio'],
followers: snapshot['followers'],
following: snapshot['following'],
);
}
}
这是我的用户提供者。user_provider
class UserProvider with ChangeNotifier {
User? myUser;
final AuthMethods _authMethods = AuthMethods();
User get getUser => myUser!;
defineUser(String uid) async {
CollectionReference refUsers =
FirebaseFirestore.instance.collection('users');
DocumentSnapshot doc = await refUsers.doc(uid).get();
User thisUser = User.fromSnap(doc);
myUser = thisUser;
notifyListeners();
return thisUser;
}
updateUserInfo(User updatedUser, String currentUserId) async {
myUser?.bio = updatedUser.bio;
myUser?.photoUrl = updatedUser.photoUrl;
myUser?.username = updatedUser.username;
notifyListeners();
await DatabaseMethods().upDateUsersInfo(updatedUser, currentUserId);
}
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
myUser = user;
notifyListeners();
}
}
这是我的聊天室chat_roomsclass ChatRooms extends StatefulWidget {
@override
_ChatRoomsState createState() => _ChatRoomsState();
}
class _ChatRoomsState extends State<ChatRooms> {
Stream<QuerySnapshot>? mySnapshot;
int? chatCount = 0;
TextEditingController searchController = TextEditingController();
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
@override
void dispose() {
searchController.dispose();
super.dispose();
}
getChatsCount() async {
QuerySnapshot snapshot = await refUsers.get();
void setStateIfMounted(f) {
if (mounted) setState(f);
}
setStateIfMounted(() {
chatCount = snapshot.docs.length - 1;
});
}
@override
void initState() {
getChatsCount();
super.initState();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
key: _scaffoldKey,
body: Column(
children: [
Container(
height: 13.5,
),
Container(
height: (1 / 6.7),
width: double.infinity,
color: Colors.grey[200],
),
Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: TextField(
onChanged: (val) async {
Stream<QuerySnapshot> snapshot = refUsers
.where('username',
isGreaterThanOrEqualTo: searchController.text)
.snapshots();
setState(() {
mySnapshot = snapshot;
});
},
controller: searchController,
decoration: InputDecoration(
prefixIcon: Icon(
Icons.search,
color: kGreenColor,
size: 22.0,
),
hintText: 'Search',
hintStyle:
myGoogleFont(Colors.black, 13.5, FontWeight.w500),
contentPadding: EdgeInsets.symmetric(horizontal: 10),
isDense: true,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none),
),
),
Expanded(
child: StreamBuilder<QuerySnapshot>(
stream: mySnapshot == null ? refUsers.snapshots() : mySnapshot,
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(
child: CircularProgressIndicator(),
);
else {
chatCount = (snapshot.data!).docs.length;
return ListView.builder(
// reverse: true,
itemCount: (snapshot.data!).docs.length,
itemBuilder: (context, index) {
User friendUser =
User.fromSnap((snapshot.data!).docs[index]);
String myUserId =
Provider.of<UserProvider>(context, listen: false)
.myUser!
.uid;
if (friendUser.uid != myUserId) {
return UserTile(friendUser);
} else
return Container();
});
}
},
),
)
],
),
),
);
}
}
很可能User.fromSnap
中的snap
对其某些值返回null
。为了解决这个你应该做以下:
- 首先,您应该确保值不是来自API/DB/任何快照来源的
null
; - 对于
null
的,默认为另一个值,像下面的?? ?条件表达式中的操作符;
static User fromSnap(DocumentSnapshot snap) {
var snapshot = snap.data() as Map<String, dynamic>;
return User(
username: snapshot['username'] ?? 'Unknown',
uid: snapshot['uid'] ?? '0000000000',
email: snapshot['email'] ?? '',
photoUrl: snapshot['photoUrl'] ?? '',
bio: snapshot['bio'] ?? '',
followers: snapshot['followers'] ?? [],
following: snapshot['following'] ?? [],
);
}