跟随Flutter Firebase codelab时FirebaseAnimatedList itemBuilder报错求助
Hey there! I’ve run into this exact issue before when working with FirebaseAnimatedList—let’s get it sorted out (pun intended 😉).
The Root Cause
The error pops up because Dart’s type inference isn’t correctly recognizing that a and b are DataSnapshot objects, and it’s treating the function’s return value as dynamic instead of the required int. The sort parameter of FirebaseAnimatedList explicitly expects a function with the signature (DataSnapshot, DataSnapshot) → int, but your current code is being inferred as (dynamic, dynamic) → dynamic—which doesn’t match.
The Quick Fix
All you need to do is explicitly type the parameters in your sort function to remove the ambiguity. Update your sort line to this:
sort: (DataSnapshot a, DataSnapshot b) => b.key.compareTo(a.key)
Why This Works
- By specifying
DataSnapshotforaandb, Dart now knows exactly what types these parameters are. It can then validate thatkey(a String) has acompareTomethod that returns anint—which perfectly matches the required return type for the sort function. - This small change eliminates the type mismatch that was throwing the error.
A Quick Double-Check
If you’re still seeing issues, make sure you’ve imported the correct Firebase package (usually firebase_database) so that DataSnapshot is recognized in your code. Most of the time though, this explicit type annotation is all you need to fix the problem.
内容的提问来源于stack exchange,提问作者Colin Burke

