首页 > 解决方案 > Flutter 中基于当前状态显示 Widget

问题描述

我的基本意图是根据我当前的状态显示一个小部件。假设,当用户单击一个按钮时,我使用该setState()方法将 a 的值设置currentPage2

onTabChangedListener: (position, title, color) {
       setState(() {
         currentPage = position;
...

当它是时2,我想显示以下小部件而不是当前显示的小部件。我已经尝试过if/else案例,但似乎不是这样。我也讨论过这个和这个,但我不清楚实施。我了解有状态小部件的工作原理 - 只需要一个与我的问题类似的代码示例。

// Widget I want to display when currentPage state is changed to 2.

  Widget _buildContent() {
    return Positioned(
      bottom: 50,
      left: 25,
      right: 25,
      child: Container(
        color: Theme.of(context).backgroundColor,
        child: Column(
          children: <Widget>[
//            _buildTextField("Some Text"),
            _buildLoginButton(),
            SizedBox(height: 20),
            RichText(
              text: TextSpan(
                text: "Some Text",
                style: TextStyle(
                  fontSize: 10.5,
                  fontWeight: FontWeight.w300,
                  letterSpacing: 1,
                ),
                children: [
                  TextSpan(
                    text: "Another Text",
                    style: TextStyle(
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

注意:我的当前代码的完整页面可在此处获得

标签: flutterflutter-layout

解决方案


这是我在我的代码中使用的东西。将您要显示的所有页面放在一个Stack带有OffstageWidget 中。Offstage如果 offstage 条件为真,小部件将隐藏(使其“offstage”)。

Stack(
          children: <Widget>[
            Offstage(
              offstage: 0 != _currentBottomBarIndex,
              child: PageOne(),
            ),
            Offstage(
              offstage: 1 != _currentBottomBarIndex,
              child: PageTwo(),
            ),
            Offstage(
              offstage: 2 != _currentBottomBarIndex,
              child: PageThree(),
            ),
            Offstage(
              offstage: 3 != _currentBottomBarIndex,
              child: PageFour(),
            ),
          ],
        ),

推荐阅读