【发布时间】:2018-08-10 03:51:10
【问题描述】:
我目前正在通过 Flutter Firebase 代码实验室here。
我已完成所有步骤,但在尝试使用 FirebaseAnimatedList 小部件的 itemBuilder 时遇到两个错误。
错误 1
与sort: (a, b) => b.key.compareTo(a.key)相关:
函数表达式类型“(动态,动态)→动态”不是类型“(DataSnapshot,DataSnapshot)→int”。这意味着它的参数或返回类型与预期不匹配。考虑更改参数类型或返回的类型。
我是否需要将(a,b) 转换为DataSnapshot?
错误 2
与FirebaseAnimatedList 的itemBuilder 相关。
参数类型'(BuildContext, DataSnapshot, Animation, int) → dynamic'不能分配给参数类型'(BuildContext, DataSnapshot, Animation) → Widget'。
在这种情况下,似乎需要传入索引,并且ChatMessage 正在返回错误的类型。我不确定如何解决这些问题。
下面是我的代码。
ChatScreenState 类的构建函数
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text('friendlychat'),
),
body: Column(
children: <Widget>[
Flexible(
child: FirebaseAnimatedList(
query: reference,
sort: (a, b) => b.key.compareTo(a.key),
padding: EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return ChatMessage(snapshot: snapshot, animation: animation);
},
),
),
Divider(height: 1.0),
Container(
decoration: BoxDecoration(color: Theme.of(context).cardColor),
child: _buildTextComposer(),
)
],
));
}
ChatMessage类
class ChatMessage extends StatelessWidget {
ChatMessage({this.snapshot, this.animation});
final DataSnapshot snapshot;
final Animation animation;
@override
Widget build(BuildContext context) {
return SizeTransition(
sizeFactor: CurvedAnimation(parent: animation, curve: Curves.easeOut),
axisAlignment: 0.0,
child: Container(
margin: EdgeInsets.symmetric(vertical: 10.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(right: 16.0),
child: CircleAvatar(
backgroundImage:
NetworkImage(snapshot.value['senderPhotoUrl'])),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(snapshot.value['senderName'],
style: Theme.of(context).textTheme.subhead),
Container(
margin: EdgeInsets.only(top: 5.0),
child: Text(snapshot.value['text']),
),
],
),
),
],
),
));
}
}
更新了FirebaseAnimatedList的代码:
FirebaseAnimatedList(
query: reference,
sort: (DataSnapshot a, DataSnapshot b) =>
b.key.compareTo(a.key),
padding: EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation) {
return ChatMessage(snapshot: snapshot, animation: animation);
},
),
【问题讨论】: