转到不同页面时如何保持计时器状态?

时间:2020-04-13 02:30:40

标签: flutter

因此,当我在textfield中输入时间时,该时间会自动格式化为xx:xx格式,然后按播放按钮,计时器将按预期倒数并停止在0。问题是当我切换时使用底部导航栏的页面,页面状态不会保存,时钟会重置为00:00。

所以我的问题是如何保存页面状态,以便即使我转到其他页面或离开应用程序,计时器也将运行?我使用以下方法,但实际上不起作用:

 final Key homeKey = PageStorageKey('HomePage');
  final Key calendarKey = PageStorageKey('CalendarPage');
  final Key statisticsKey = PageStorageKey('StatisticsPage');
  final Key profileKey = PageStorageKey('ProfilePage');

  HomePage homePage;
  CalendarPage calendarPage;
  StatisticsPage statisticsPage;
  ProfilePage profilePage;

  List<Widget> pages; // List of all pages
  Widget currentPage; // Current Selected Page

  final PageStorageBucket bucket = PageStorageBucket();

  @override
  void initState() {
    homePage = HomePage(
      key: homeKey,
      dataSet: dataList,
    ); //

    calendarPage = CalendarPage(
      key: calendarKey,
      dataSet: dataList,
    );

    statisticsPage = StatisticsPage(
      key: statisticsKey,
    );

    profilePage = ProfilePage(
      key: profileKey,
    );

    pages = [homePage, calendarPage, statisticsPage, profilePage];

    currentPage = homePage;
    super.initState();
  }

  int _currentTab = 0;

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      backgroundColor: Colors.white,
      body: PageStorage(
        child: currentPage,
        bucket: bucket,
      ),
      bottomNavigationBar:
          _buildBottomNavigationBar(), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  Widget _buildBottomNavigationBar() {
    return BottomNavigationBar(
      backgroundColor: Colors.white,
      type: BottomNavigationBarType.fixed,
      currentIndex: _currentTab,
      onTap: (int index) {
        setState(() {
          _currentTab = index;
          currentPage = pages[index];
        });
      },
      items: <BottomNavigationBarItem>[
        BottomNavigationBarItem(
          icon: Icon(Icons.home),
          title: Text("Home"),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.calendar_today),
          title: Text("Calendar"),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.multiline_chart),
          title: Text("Statistics"),
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.verified_user),
          title: Text("Profile"),
        ),
      ],
    );
  }

Timer Page

GIF of the Problem

1 个答案:

答案 0 :(得分:0)

我有同样的问题,我的临时解决方案是将所有页面都放在 PageView

正文:PageView(...)

并禁用PageView滚动。