【发布时间】:2021-03-05 17:43:32
【问题描述】:
我有一个底部导航栏,其中有一个列表页面,该页面使用 bloc 表示状态。
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。
【问题讨论】:
-
只是出于好奇,为什么你有两个 Scaffold 嵌套在一个父 Scaffold 中?
-
它们是占位符。仍在研究那部分。