多次调用 Flutter 构建

lok*_*oki 6 state flutter 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(),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

问题是build被调用了 4 次。这会导致事件获取列表 4 次。

不知道在哪里添加事件以防止重新构建。

如果我在有状态小部件的initState. 在从小部件树中获取 bloc 时,Bloc 无法识别上下文中的 ListBloc beeing。

Tah*_*lik 6

最好的方法是在主路线(包含底部导航的路线)的 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(),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


7ma*_*ada 3

根据官方文档,您可以将 StatefulWidget 类与 KeepAlive 一起使用(将孩子标记为需要保持活动状态,即使它位于惰性列表中,否则会删除它)。

在代码中:

class YourStatefulWidget extends StatefulWidget {

//add with AutomaticKeepAliveClientMixin to the state class

class _YourStatefulWidgetState extends State<YourStatefulWidget > with AutomaticKeepAliveClientMixin {

  //add  super.build(context) under the build method
  Widget build(BuildContext context) {
  super.build(context);

  return //your widget

   @override
   bool get wantKeepAlive => true;
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以通过使用状态管理类中的布尔值来进行逻辑修复,因为如果小部件被重建,该值不会改变。