首页 > 解决方案 > 导航到新路线并处理之前的状态

问题描述

我的主页上有一个计时器,当我导航到命名路由时,计时器继续工作并希望它处理,所以我使用 pushReplacement 到新屏幕并返回,现在我的问题是我丢失了我在 main 中初始化的侧栏,我可以将它移动到布局小部件并重建它,但它应该发生一次,所以在我看来这是错误的方式 pushReplacement 真的需要吗?还有其他方法可以实现这种行为吗?

这是我的主要内容:

 @override
  Widget build(BuildContext context) {
    print('build');

    return MultiProvider(
      providers: _providers,
      child: MaterialApp(
        title: 'myProject',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: AppColors.primaryBlack,
          brightness: Brightness.light,
        ),
        home: FutureBuilder(
          future: _initFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return Scaffold(
                body: Stack(children: [
                  AppLayout(
                    currentIndex: 0,
                  ),
                  SideBar(),
                ]),
              );
            } else {
              return SplashScreen();
            }
          },
        ),
      ),
    );
  }

我的路由页面包含我推送和替换的页面:

class RoutePage extends StatelessWidget {
  final String back;
  final Widget child;
  final Color color;
  final dynamic args;
  const RoutePage({Key key, this.child, this.color, this.args, this.back})
      : super(key: key);

  void navBack(context) {
    switch (back) {
      case "home":
        AppRoutes.home(context, 0);
        break;
      case "leagues":
        AppRoutes.home(context, 1);
        break;
      case "liveScores":
        AppRoutes.home(context, 2);
        break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        if (this.back != null) {
          navBack(context);
        } else {
          Navigator.pop(context);
        }

        return Future.value(true);
      },
      child: Scaffold(
        body: Stack(
          children: [
            child,
            Positioned(
                top: 30,
                left: 30,
                child: IconButton(
                  color: color != null ? color : Colors.black,
                  icon: Icon(Icons.arrow_back),
                  onPressed: () {
                    if (this.back != null) {
                      navBack(context);
                    } else {
                      Navigator.pop(context);
                    }
                  },
                )),
          ],
        ),
      ),
    );
  }
}

approutes.home:

  static home(context, index) => Navigator.pushReplacement(
      context,
      MaterialPageRoute(
          builder: (BuildContext context) => AppLayout(currentIndex: index)));

标签: flutter

解决方案


推荐阅读