【发布时间】:2020-01-11 16:31:06
【问题描述】:
我仍然是流和 bloc 模式的初学者。
我想做以下事情:
- 触发事件。
- 根据事件获取对象的状态
- 将此对象作为 JSON 存储在数据库中。
所有示例都在展示,如何使用 BlocBuilder 在小部件中显示对象。但我不需要显示值,只获取并存储它。我不知道如何将值放入变量中。
我该怎么做?在 View 类中,我正在调度事件,但现在我需要知道如何在不使用 BlocBuilder 的情况下将对象恢复为状态。
以下是详细信息:
集团
class SchoolBloc extends Bloc<SchoolEvent, SchoolState> {
final SchoolRepository _schoolRepository;
StreamSubscription _schoolSubscription;
SchoolBloc({@required SchoolRepository schoolRepository})
: assert(schoolRepository != null),
_schoolRepository = schoolRepository;
@override
SchoolState get initialState => SchoolsLoading();
@override
Stream<SchoolState> mapEventToState(SchoolEvent event) async* {
if (event is LoadSchool) {
yield* _mapLoadSchoolToState();
Stream<SchoolState> _mapLoadSchoolToState(LoadSchool event) async* {
_schoolSubscription?.cancel();
_schoolSubscription = _schoolRepository.school(event.id).listen(
(school) {
SchoolLoaded(school);
}
);
}
活动
@immutable
abstract class SchoolEvent extends Equatable {
SchoolEvent([List props = const []]) : super(props);
}
class LoadSchool extends SchoolEvent {
final String id;
LoadSchool(this.id) : super([id]);
@override
String toString() => 'LoadSchool';
}
州
@immutable
abstract class SchoolState extends Equatable {
SchoolState([List props = const []]) : super(props);
}
class SchoolLoaded extends SchoolState {
final School school;
SchoolLoaded([this.school]) : super([school]);
@override
String toString() => 'SchoolLoaded { school: $school}';
}
查看
class CourseView extends StatefulWidget {
@override
State<StatefulWidget> createState() => _CourseViewState();
}
class _CourseViewState extends State<CourseView> {
@override
initState() {
super.initState();
print("this is my init text");
final _schoolBloc = BlocProvider.of<SchoolBloc>(context);
_schoolBloc.dispatch(LoadSchool("3kRHuyk20UggHwm4wrUI"));
// Here I want to get back the school object and save it to a db
}
测试失败
出于测试目的,我做了以下操作:
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:teach_mob/core/blocs/school/school.dart';
class CourseView extends StatefulWidget {
@override
State<StatefulWidget> createState() => _CourseViewState();
}
class _CourseViewState extends State<CourseView> {
@override
void initState() {
super.initState();
BlocProvider.of<SchoolBloc>(context)
.dispatch(LoadSchool("3kRHuyk20UggHwm4wrUI"));
}
@override
Widget build(BuildContext context) {
return BlocListener<SchoolBloc, SchoolState>(
listener: (context, state) {
print("BlocListener is triggered");
},
child: Text("This is a test")
);
}
}
LoadSchool 事件被触发。 BlocListener的child属性中的文本显示出来了,但是应该打印“BlocListener is triggered”的监听函数没有被执行。
【问题讨论】:
标签: flutter