我有一个底部导航栏,它有一个列表页面,该页面使用状态块。
class _MainPageState extends State<MainPage> {
int _index = 0;
@override
Widget build(BuildContext context) {
final List<Widget> _widgets = [
const ListPage(),
Scaffold(),
Scaffold(),
];
return Scaffold(
body: IndexedStack(
index: _index,
children: _widgets,
),
bottomNavigationBar: BottomNavigationBar(
...
class ListPage extends StatelessWidget {
const ListPage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) =>
getIt<ListBloc>()..add(const ListEvent.load(limit: 10)),
child: SafeArea(
child: Scaffold(
appBar: AppBar(),
body: const List(),
),
),
);
}
}
问题是build
被调用 4 次。这会导致事件获取列表 4 次。不知道在哪里添加事件以防止重新构建。
如果我在 statefull 小部件的
initState
中添加事件.在从小部件树中获取 bloc 时,Bloc 无法识别上下文中的 ListBloc beeing。
最佳答案
最好的方法是在您的主要路线(包含底部导航的路线)的 initState 中添加事件。如下面的代码所示。
class _MainPageState extends State<MainPage> {
int _index = 0;
@override
void initState() {
super.initState();
getIt<ListBloc>().add(const ListEvent.load(limit: 10));
}
@override
Widget build(BuildContext context) {
final List<Widget> _widgets = [
const ListPage(),
Scaffold(),
Scaffold(),
];
return Scaffold(
body: IndexedStack(
index: _index,
children: _widgets,
),
bottomNavigationBar: BottomNavigationBar(
...
class ListPage extends StatelessWidget {
const ListPage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) =>
getIt<ListBloc>(),
child: SafeArea(
child: Scaffold(
appBar: AppBar(),
body: const List(),
),
),
);
}
}
关于多次调用 Flutter 构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64961138/