【问题标题】:Flutter - setState only updating after the second click and it renders the old valueFlutter - setState 仅在第二次单击后更新并呈现旧值
【发布时间】:2020-06-08 06:14:41
【问题描述】:

当用户单击bottomNavigationBar 项目时,我正在尝试更新appbar 文本,该项目还通过名为chooseTab() 的函数呈现正文。我已将 appBarText 放置在 chooseTab() 函数内的开关盒中,但 setState 直到第二次单击才更新 appBar 文本。即使它呈现它也会呈现 appBar 文本的先前值。身体渲染没有任何问题。

class HomeScreen extends StatefulWidget {
  static const String id = 'home_screen';

  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String _appBarText = 'Dashboard';
  int _tabIndex = 0;
  GlobalKey _bottomNavigationKey = GlobalKey();

  chooseTab() {
    switch (this._tabIndex) {
      case 0:
        _appBarText = 'Dashboard';
        return new DashboardScreen();
        break;

      case 1:
        _appBarText = 'Cards';

        return new CardScreen();
        break;

      case 2:
        _appBarText = 'Receipts';

        return new ReceiptsScreen();
        break;

      case 3:
        _appBarText = 'Settings';

        return new SettingsScreen();
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: kBackground,
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: AppBar(
          title: Text(
            _appBarText,
          ),
        ),
        body: chooseTab(),
        bottomNavigationBar: CurvedNavigationBar(
          key: _bottomNavigationKey,
          index: _tabIndex,
          height: 70.0,
          items: <Widget>[
            Icon(Icons.home, size: 25),
            Icon(Icons.credit_card, size: 25),
            Icon(Icons.receipt, size: 25),
            Icon(Icons.person, size: 25),
          ],
          onTap: (int tappedIndex) {
            setState(() {
              this._tabIndex = tappedIndex;
            });
          },
          color: Colors.grey[900],
          buttonBackgroundColor: Colors.grey[900],
          backgroundColor: Colors.transparent,
          animationCurve: Curves.easeInOut,
          animationDuration: Duration(milliseconds: 600),
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter setstate


    【解决方案1】:

    这是因为当您触发 setState 时,您的小部件树会重新呈现,但您的 switch case 在 AppBar 显示之后设置为 _appBarText 并且是时候显示正文内容了

    你可以这样列出你的头衔:

    List<String> titles = [
       'Dashboard',
       'Cards',
       'Receipts',
       'Settings'
    ];
    

    然后你的appBar 应该是这样的:

    appBar: AppBar(
        title: Text(
            titles[_tabIndex],
        ),
    ),
    

    尽量不要使用this关键字:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      相关资源
      最近更新 更多