【问题标题】:How to go back to previous screen by clicking on bottom navigation bar item in Flutter如何通过单击 Flutter 中的底部导航栏项返回上一屏幕
【发布时间】:2021-12-11 15:03:12
【问题描述】:

我正在使用这个库persistent_bottom_nav_bar 来显示底部导航栏,即使在导航到新屏幕时也是如此。现在有两个主要页面Page1Page2Page1 使用home 的图标,而Page2 使用search 的图标。在Page1 中包含一个导航到名为NewPage 的新屏幕的按钮。我想要实现的是,如果我从Page1 导航到NewPage,并且如果我决定返回到上一个屏幕Page1通过单击底部的homeicon。那么如何单击底部项目并返回上一个屏幕?希望你能理解我的问题

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Demo',
      home: HomeScaffold(),
    );
  }
}

class HomeScaffold extends StatefulWidget {
  @override
  _HomeScaffoldState createState() => _HomeScaffoldState();
}

class _HomeScaffoldState extends State<HomeScaffold> {
  late PersistentTabController _controller;

  @override
  void initState() {
    super.initState();
    _controller = PersistentTabController(initialIndex: 0);
  }

  List<Widget> _buildScreens() {
    return [
      Page1(),
      Page2(),
    ];
  }

  List<PersistentBottomNavBarItem> _navBarsItems() {
    return [
      _buildBottomNavBarItem('Page 1', Icons.home),
      _buildBottomNavBarItem('Page 2', Icons.search),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return PersistentTabView.custom(
      context,
      controller: _controller,
      screens: _buildScreens(),
      confineInSafeArea: true,
      itemCount: 2,
      handleAndroidBackButtonPress: true,
      stateManagement: true,
      screenTransitionAnimation: ScreenTransitionAnimation(
        animateTabTransition: true,
        curve: Curves.ease,
        duration: Duration(milliseconds: 200),
      ),
      customWidget: CustomNavBarWidget(
        items: _navBarsItems(),
        onItemSelected: (index) {
          setState(() {
            _controller.index = index; // go back to previous screen if i navigate to new screen
          });
        },
        selectedIndex: _controller.index,
      ),
      // ),
    );
  }
}

class CustomNavBarWidget extends StatelessWidget {
  final int? selectedIndex;
  final List<PersistentBottomNavBarItem> items;
  final ValueChanged<int>? onItemSelected;

  CustomNavBarWidget({
    Key? key,
    this.selectedIndex,
    required this.items,
    this.onItemSelected,
  });

  Widget _buildItem(PersistentBottomNavBarItem item, bool isSelected) {
    return Container(
      alignment: Alignment.center,
      height: kBottomNavigationBarHeight,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Flexible(
            child: IconTheme(
              data: IconThemeData(
                  size: 26.0,
                  color: isSelected
                      ? (item.activeColorSecondary == null
                          ? item.activeColorPrimary
                          : item.activeColorSecondary)
                      : item.inactiveColorPrimary == null
                          ? item.activeColorPrimary
                          : item.inactiveColorPrimary),
              child: isSelected ? item.icon : item.inactiveIcon ?? item.icon,
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 5.0),
            child: Material(
              type: MaterialType.transparency,
              child: FittedBox(
                  child: Text(
                item.title!,
                style: TextStyle(
                    color: isSelected
                        ? (item.activeColorSecondary == null
                            ? item.activeColorPrimary
                            : item.activeColorSecondary)
                        : item.inactiveColorPrimary,
                    fontWeight: FontWeight.w400,
                    fontSize: 12.0),
              )),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Container(
        width: double.infinity,
        height: kBottomNavigationBarHeight,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: items.map((item) {
            int index = items.indexOf(item);
            return Flexible(
              child: GestureDetector(
                onTap: () {
                  this.onItemSelected!(index);
                },
                child: _buildItem(item, selectedIndex == index),
              ),
            );
          }).toList(),
        ),
      ),
    );
  }
}

PersistentBottomNavBarItem _buildBottomNavBarItem(String title, IconData icon) {
  return PersistentBottomNavBarItem(
    icon: Icon(icon),
    title: title,
    activeColorPrimary: Colors.indigo,
    inactiveColorPrimary: Colors.grey,
  );
}

class Page1 extends StatefulWidget {
  const Page1({Key? key}) : super(key: key);

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

class _Page1State extends State<Page1> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        child: Center(
          child: TextButton(
            onPressed: () {
              Navigator.push(
                  context, CupertinoPageRoute(builder: (context) => NewPage()));
            },
            child: Text('Click'),
          ),
        ),
      ),
    );
  }
}

class Page2 extends StatefulWidget {
  const Page2({Key? key}) : super(key: key);

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

class _Page2State extends State<Page2> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.red,
      body: Container(),
    );
  }
}

class NewPage extends StatefulWidget {
  const NewPage({Key? key}) : super(key: key);

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

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(),
    );
  }
}

【问题讨论】:

    标签: flutter dart flutter-bottomnavigation


    【解决方案1】:

    您是否尝试过简单地将内置的Navigator.of(context).pop() 函数用作onPressed 回调?

    【讨论】:

    • 是的,我试过了,但是当我点击底部的home icon 时,屏幕变黑了。 onItemSelected: (index) { setState(() { _controller.index = index; Navigator.of(context).pop(); }); },
    • 你能不能从你这边试试看可能是我做错了。
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 2021-11-27
    • 2020-11-28
    • 2020-02-11
    • 1970-01-01
    • 2020-06-10
    • 2020-09-22
    • 2022-12-12
    相关资源
    最近更新 更多