我有一个有状态的小部件和一个简单的块,并且我使用streamBuilder来构建页面。 当我在小部件的build方法中使用bloc时,当输入新数据时,它永远不会更新。 我确定该集团消息已被接收。
不确定要怎么做才能做到这一点?
class ChooseCompanyPage extends StatefulWidget {
@override
_ChooseCompanyPageState createState() => _ChooseCompanyPageState();
}
class _ChooseCompanyPageState extends State<ChooseCompanyPage> {
final bloc = ChooseCompanyBloc();
List<CompanyModel> companyList;
@override
void initState() {
super.initState();
bloc.state.listen(
(event) {
if (event is JumpToLoginPage) {
Navigator.of(context).pushReplacementNamed('loginPage');
}
},
);
bloc.action.add(ChooseCompangeInit());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Choose your company'),
),
body: _buildBody(context));
}
Widget _buildBody(BuildContext context) {
return StreamBuilder<ChooseCompanyBasicEvent>(
stream: bloc.state,
initialData: ChooseCompangeInit(),
builder: (BuildContext context, snap) {
final data = snap.data;
if (data is ChooseCompangeInit) {
return Center(
child: CircularProgressIndicator(),
);
}
if (data is GetCompanyData) {
return RefreshIndicator(
onRefresh: () {
bloc.action.add(ChooseCompanyRequest());
},
child: ListView.builder(
itemCount: data.companyList.length,
itemBuilder: (context, index) {
final company = data.companyList[index];
return Column(
children: <Widget>[
ListTile(
title: Text(company.name),
onTap: () {
support.kiraShowYesOrNoDialog(
context: context,
title: 'Tip',
indicator: 'Choose ${company.name}?',
okCallBack: () {
bloc.action.add(ChooseACompany(company));
});
},
),
Divider(
height: 1,
)
],
);
},
),
);
}
},
);
}
}
集团代码就是这样
final Sink<ChooseCompanyBasicEvent> action;
final Stream<ChooseCompanyBasicEvent> state;
ChooseCompanyBloc._(this.action, this.state);
factory ChooseCompanyBloc() {
final action = PublishSubject<ChooseCompanyBasicEvent>();
final state = action.switchMap((event) {
return _generateState(event);
});
action.add(ChooseCompangeInit());
return ChooseCompanyBloc._(action, state);
}
void dispose() {
action.close();
}
/// choose Company business logic
static Stream<ChooseCompanyBasicEvent> _generateState(
ChooseCompanyBasicEvent event) async* {
if (event is ChooseCompanyRequest) {
yield event;
try {
final companyList = await _getCompanyList();
yield GetCompanyData(companyList);
} catch (e) {
yield GetDataFailed('');
}
}
if (event is ChooseACompany) {
final chooseCompany = event.chosenCompany;
await _saveCompanyID(chooseCompany);
yield JumpToLoginPage();
}
if (event is ChooseCompangeInit) {
yield event;
try {
final companyList = await _getCompanyList();
if (companyList.length == 0) {
yield EmtpyData();
} else {
yield GetCompanyData(companyList);
}
} catch (e) {
yield GetDataFailed('');
}
}
}
当新数据进入时,streamBuilder不称为构建方法