在Flutter中,可以使用BottomNavigationBar结合PageView来实现底部导航栏切换页面的功能。以下是一个简单的实例代码:
import 'package:flutter/material.dart';
 
void main() => runApp(MyApp());
 
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}
 
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
 
class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  final _pageList = <Widget>[
    Icon(Icons.home),
    Icon(Icons.search),
    Icon(Icons.add),
    Icon(Icons.favorite),
    Icon(Icons.person),
  ];
 
  void _onTap(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        children: <Widget>[
          Icon(Icons.home),
          Icon(Icons.search),
          Icon(Icons.add),
          Icon(Icons.favorite),
          Icon(Icons.person),
        ],
        controller: PageController(initialPage: _currentIndex),
        onPageChanged: _onTap,
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: _onTap,
        items: [
          BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
          BottomNavigationBarItem(icon: Icon(Icons.search), title: Text('Search')),
          BottomNavigationBarItem(icon: Icon(Icons.add), title: Text('Add')),
          BottomNavigationBarItem(icon: Icon(Icons.favorite), title: Text('Favorite')),
          BottomNavigationBarItem(icon: Icon(Icons.person), title: Text('Profile')),
        ],
      ),
    );
  }
}这段代码创建了一个HomePage状态ful widget,它维护了当前选中的页面索引_currentIndex。_onTap方法用于更新当前索引,并且通过setState来重新构建页面。PageView控制了页面的展示,而BottomNavigationBar控制了底部导航栏的行为。每当用户点击底部导航栏的项时,_onTap方法被调用,并且PageView的页面会切换到对应的索引页面。