我正在尝试创建一个AnimatedList
使用bloc
模式,但遇到了一些问题。
当我将 initialItemsCount 设置为AnimatedList
时state.itemList.length
,它不会构建。虽然当我在 's listener 中打印出state.itemList
(来自ListBloc
)时,BlocConsumer
它会打印出itemList
.
那么,问题是为什么这不起作用?
我尝试做同样的事情ListView.builder
并且效果很好。我是否遗漏了某些东西,或者AnimatedList
甚至不应该使用 bloc 工作?
这是一些示例代码,对于这种情况来说非常简单:
MyApp 类:
class _MyAppState extends State<MyApp> {
final key = GlobalKey<AnimatedListState>();
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => ListBloc()..add(LoadList()),
child: MaterialApp(
home: SafeArea(
child: BlocConsumer<ListBloc, ListState>(
listener: (_, state) {
print(state.itemList);
},
builder: (context, state) => Scaffold(
body: Column(
children: [
Expanded(
child: AnimatedList(
key: key,
initialItemCount: state.itemList.length,
itemBuilder: (context, index, animation) {
return Item(
animation: animation,
index: index,
text: state.itemList[index],
onTap: () => removeItem(index, state.itemList));
},
),
),
],
),
),
),
),
),
);
}
void removeItem(int index, List<String> items) {
final item = items.removeAt(index);
key.currentState?.removeItem(
index,
(context, animation) => Item(
animation: animation,
index: index,
text: items[index],
onTap: () => removeItem(index, items)));
}
}
物品类别:
class Item extends StatelessWidget {
final Animation<double> animation;
final int index;
final String text;
final VoidCallback onTap;
const Item(
{required this.animation,
required this.index,
required this.text,
required this.onTap,
Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return ScaleTransition(
scale: animation,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
onTap: onTap,
child: Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(text),
),
)),
),
);
}
}
集团:
class ListEvent extends Equatable {
const ListEvent();
@override
List<Object> get props => [];
}
class LoadList extends ListEvent {}
class ListState extends Equatable {
final List<String> itemList;
const ListState({required this.itemList});
@override
List<Object> get props => [itemList];
}
class ListBloc extends Bloc<ListEvent, ListState> {
ListBloc() : super(ListState(itemList: []));
@override
Stream<ListState> mapEventToState(ListEvent event) async* {
if (event is LoadList) {
var items = ['1', '2', '3', '4', '5', '6'];
yield ListState(itemList: items);
}
}
}
谢谢!