我有一个使用bloc进行管理的页面
这是home_state.dart
import 'package:banha/data/models/category.dart';
import 'package:flutter/material.dart';
abstract class HomeState {
HomeState() : super();
}
class HomeInitial extends HomeState {}
class UpdateCats extends HomeState {
final List<Category> cats;
final int rand;
UpdateCats({@required this.cats,@required this.rand}){
print(this.cats);
print(this.rand);
}
}
和home_bloc.dart
(注意:随机数只是为了确保状态与上一个相差)
import 'dart:math';
import 'package:banha/data/models/category.dart';
import 'package:banha/data/network/categories.dart';
import 'package:banha/ui/tabs/home/bloc/home_events.dart';
import 'package:banha/ui/tabs/home/bloc/home_states.dart';
import 'package:bloc/bloc.dart';
class HomeBloc extends Bloc<HomeEvents, HomeState> {
getAllCats() {
dispatch(HomeGetCategories());
}
HomeBloc() : super();
@override
HomeState get initialState => HomeInitial();
@override
Stream<HomeState> mapEventToState(HomeEvents event) async* {
if (event is HomeGetCategories) {
yield* _getCats();
}
}
Stream<HomeState> _getCats() async* {
print("getting cats");
List<Category> newCats;
await Network_getAllCategories().then((List<Category> cats) {
newCats = cats;
});
yield UpdateCats(cats: newCats, rand: Random().nextInt(21312545));
}
}
和页面小部件:
import 'package:banha/ui/category/category.dart';
import 'package:banha/ui/tabs/home/bloc/home_bloc.dart';
import 'package:banha/ui/tabs/home/bloc/home_states.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ListingsWidget extends StatefulWidget {
@override
_ListingsWidgetState createState() => _ListingsWidgetState();
}
class _ListingsWidgetState extends State<ListingsWidget> {
final HomeBloc _homeBloc = HomeBloc();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
height: 130,
padding: EdgeInsets.only(top: 10, bottom: 10),
child: BlocListener(
bloc: _homeBloc,
listener: (context, state) {
print(state);
},
child: BlocBuilder<HomeBloc, HomeState>(
bloc: _homeBloc,
builder: (BuildContext context,HomeState state) {
if(state is UpdateCats){
print(state.cats);
}
return ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
InkWell(
borderRadius: BorderRadius.circular(1000),
onTap: () {
HomeBloc().getAllCats();
// Navigator.push(context, CupertinoPageRoute(builder: (context) => CategoryPage()));
},
....
问题在于,在视图(窗口小部件)中,BlocBuilder最初只是被调用一次,但是当我尝试使用HomeBloc().getAllCats();
测试更改状态,然后使用以下代码打印新状态时:
if(state is UpdateCats){
print(state.cats);
}
什么也没有发生(Builder不再被调用),我的代码怎么了?
答案 0 :(得分:0)
我在根窗口小部件(即HomePage)中添加了BlocProvider
,并解决了该问题。
答案 1 :(得分:0)
问题在这里:
...
onTap: () {
...
HomeBloc().getAllCats();
...
},
...
应为_homeBloc.getAllCats();