问题
I just learn about how can i use Bloc
in flutter applications and my simple app i have some separated view class as App
and MainPage
and i implemented simple Bloc
pattern to handle click event on some widgets such as button
after running application my implemented bloc pattern only work once and show message in console and after click again that don't work to show message
my main.dart
class
void main() {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
title: Strings.appName,
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: App(),
));
}
class App extends StatefulWidget {
final HomeBloc homeBloc = HomeBloc();
@override
State<App> createState() => MainPage();
}
MainPage
class:
class MainPage extends State<App> {
@override
void initState() {
super.initState();
}
HomeBloc get _homeBloc => widget.homeBloc;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: Strings.appName,
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: BlocBuilder<HomeEvent,HomeState>(
bloc: _homeBloc,
builder: (BuildContext context, HomeState state) {
if (state is HandleDrawerMenuClick) {
_onWidgetDidBuild(() {
print("clicked on drawer menu");
});
}
return Scaffold(
body: Center(
child: RaisedButton(
child: Text('ddddddddd'),
onPressed: () {
_homeBloc.dispatch(OnDrawerMenuClicked());
},
),
),
);
}),
);
}
@override
void dispose() {
_homeBloc.dispose();
super.dispose();
}
void _onWidgetDidBuild(Function callback) {
WidgetsBinding.instance.addPostFrameCallback((_) {
callback();
});
}
}
HomeBloc
class:
class HomeBloc extends Bloc<HomeEvent, HomeState> {
@override
HomeState get initialState => HomeState();
@override
Stream<HomeState> mapEventToState(HomeEvent event) async* {
if (event is OnDrawerMenuClicked) {
yield HandleDrawerMenuClick();
}
}
}
HomeEvent
class:
class HomeEvent extends Equatable {
HomeEvent([List props = const []]) : super(props);
}
class OnDrawerMenuClicked extends HomeEvent {
OnDrawerMenuClicked() : super([]);
@override
String toString() => 'OnDrawerMenuClicked clicked';
}
HomeState
class:
class HomeState extends Equatable{
HomeState([List props = const[]]):super(props);
}
class HandleDrawerMenuClick extends HomeState{
@override
String toString()=>'HandleDrawerMenuClick';
}
i think problem is on HandleDrawerMenuClick
class because when i debug application, debug can go into if
statement on this line:
if (event is OnDrawerMenuClicked) {
yield HandleDrawerMenuClick();
}
and i think twice click on button couldn't trigger yield HandleDrawerMenuClick();
来源:https://stackoverflow.com/questions/56207806/flutter-simple-implementation-to-handle-click-event-with-bloc-work-once