我正在使用Bloc模式构建Flutter应用程序,并且遇到以下问题:
使用BlocBuilder(),按下按钮后,我无法从A页正确导航到B页,它将推到B页并永远循环。
使用BlocListener(),我可以在第一时间按我的按钮进行导航,而在其他新闻中不能再次进行操作。
如何正确导航?
我的代码:
class PageA extends StatelessWidget {
Movies movie;
double scale;
MovieBLoc _movieBLoc;
MovieItem({@required this.movie, this.scale});
BuildContext context;
@override
Widget build(BuildContext context) {
_movieBLoc = MovieBLoc();
this.context = context;
return BlocProvider<MovieBLoc>(
create: (context) => _movieBLoc,
child: BlocBuilder<MovieBLoc, MovieState>(
builder: (context, movieState) {
if (movieState is MovieNavigation) _onGoingToDetail();
return _itemPageView(scale, movie);
},
),
);
}
Widget _itemPageView(double scale, Movies movie) {
return LayoutBuilder(
builder: (context, constraint) {
return Align(
alignment: FractionalOffset.center,
child: Stack(
children: <Widget>[
_movieBackground(constraint, scale, movie),
_filter(constraint, scale),
_movieInfo(constraint, scale, movie),
],
),
);
},
);
}
Widget _movieInfo(BoxConstraints constraint, double scale, Movies movie) {
return Container(
width: double.infinity,
height: ((constraint.maxHeight / 100) * 65) / scale,
margin: EdgeInsets.only(left: 15, right: 15),
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
/* ... code ... */
Expanded(
flex: 2,
child: Container(
margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
child: RaisedButton(
// CLick on my button and navigate to page B
onPressed: () {
_movieBLoc.add(MoviePressed(movie: movie));
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(15))),
color: Colors.orange,
child: FittedBox(
fit: BoxFit.cover,
child: Text(
AppString.bookButtonValue,
style: TextStyle(
color: AppTheme.onSurface, fontSize: 20),
),
),
),
))
],
)
],
),
);
}
_onGoingToDetail() {
WidgetsBinding.instance.addPostFrameCallback((_) {
Navigator.of(context).pushNamed(RounterNames.pageB,
arguments: MovieDetailArgs(movie: movie));
});
}
/* ... code ... */
}
答案 0 :(得分:0)
Bloc软件包的文档带有不同的收据。
https://bloclibrary.dev/#/recipesflutternavigation?id=recipes-navigation
您肯定需要使用BlocListener。另外,请注意将Equitable与事件和状态一起使用。
因为下一个状态可能是相同的,并且如果当前状态为“ NavigateState”,并且您再次发送“ NavigationState”的新实例,则可以忽略该状态