【问题标题】:Routes in FlutterFlutter 中的路由
【发布时间】:2020-12-26 21:14:05
【问题描述】:

我是 Flutter 的新手,我正在构建一个 Flutter 应用程序,我创建了这些路由,它几乎可以工作,问题是当我返回上一个屏幕时,应该返回 HomeScreen(),相反,它返回一个先前的屏幕,即 LoginScreen()。 在这种情况下,我使用的是 Navigator.pushReplacementNamed,如果我只使用 Navigator.pushNamed,它会返回主屏幕,但选择了错误的 Text(),

int selectedIndex = 0;

最终列表类别 = ['Chat', 'Contatos', 'Grupos', 'Chamadas'];

ListView.builder(
      scrollDirection: Axis.horizontal,
      itemCount: categories.length,
      itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          onTap: () {
            setState(() {
              Navigator.pushReplacementNamed(
                  context, '/${categories[index]}');
              selectedIndex = index;
            });
          },
          child: Padding(
            padding: const EdgeInsets.symmetric(
              horizontal: 15,
              vertical: 30,
            ),
            child: Text(
              categories[index],
              style: TextStyle(
                  color: index == selectedIndex
                      ? Colors.white
                      : Colors.white60,
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  letterSpacing: 1),
            ),
          ),
        );
      }),

还有我的 Main.dart

 routes: {
    '/': (context) => MySplashScreen(),
    '/Chat': (context) => HomeScreen(),
    '/Contatos': (context) => ContactsScreen()
  },

【问题讨论】:

    标签: flutter listview routes selecteditem navigator


    【解决方案1】:

    最好看看对应的cookbook

    您在这种情况下的困惑是因为如果您使用pushNamed(),您的路由器会“堆叠”路由,而不是替换它们。然后后退按钮“弹出”堆栈。 (这是我最常用的。)如果你使用pushReplacementNamed(),这等于“pop”然后“push”,所以不会建立“stack”。

    另外,selectedIndex 在使用后退按钮时不会更改,这就是为什么在这种情况下文本仍然相同(对您来说是错误的;-))。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-04
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 2019-10-18
      • 2020-05-06
      • 2021-05-28
      相关资源
      最近更新 更多