我正在尝试在颤动中实现一个动态列表视图,可以通过点击浮动肌动蛋白按钮来增加它。但是浮动操作按钮的 onPressed 方法只更新一次。
以下是我的 UI 和颤振块代码:-
import 'package:demo/bloc/main/demo_bloc.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Demo",
home: DemoApp(),
);
}
}
class DemoApp extends StatelessWidget {
const DemoApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
lazy: false,
create: (context)=>DemoBloc([54,4,598,984,654,87,5,897,65,46,84,65,4984,]),
child: Scaffold(
appBar: AppBar(
title: Text("Demo"),
),
body: NumberList(),
floatingActionButton: BlocBuilder<DemoBloc, List<int>>(
builder: (context, state){
return FloatingActionButton(
onPressed: (){
BlocProvider.of<DemoBloc>(context).addItem(12);
}
);
},
),
),
);
}
}
class NumberList extends StatelessWidget {
const NumberList({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocBuilder<DemoBloc, List<int>>(builder: (context, state) {
return ListView.builder(
itemCount: BlocProvider.of<DemoBloc>(context).state.length,
itemBuilder: (context, index) {
return Text(
BlocProvider.of<DemoBloc>(context).state[index].toString()
);
});
});
}
}
import 'package:flutter_bloc/flutter_bloc.dart';
class DemoBloc extends Cubit<List<int>>{
DemoBloc(List<int> initialState) : super(initialState);
addItem(int value){
print("adding item to the numbers list");
state.add(value);
emit(state);
}
removeItem(){
state.removeLast();
emit(state);
}
removeItemFrom(int index){
state.removeAt(index);
emit(state);
}
}
我在 addItem() 函数中使用 print 函数,它正在执行并在控制台中打印,但列表仅更新一次。