在 Flutter 中使用 NavigationRail 和 BottomNavigationBar 创建自适应布局
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _selectedIndex = 0;
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _getBody(_selectedIndex),
bottomNavigationBar: BottomNavigationBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.settings), title: Text('Settings')),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.blue,
onTap: _onItemTapped,
),
navigationRail: NavigationRail(
selectedIndex: _selectedIndex,
onDestinationSelected: _onItemTapped,
destinations: [
NavigationRailDestination(icon: Icon(Icons.home), label: Text('Home')),
NavigationRailDestination(icon: Icon(Icons.settings), label: Text('Settings')),
],
),
);
}
Widget _getBody(int index) {
switch (index) {
case 0:
return Text('Home Screen');
case 1:
return Text('Settings Screen');
default:
return Text('Unknown screen');
}
}
}
这段代码展示了如何在Flutter中同时使用NavigationRail和BottomNavigationBar来创建一个具有导航功能的应用程序。当用户点击底部导航栏或侧边导航栏中的项目时,应用程序会更新当前显示的页面。这种方法可以使应用程序在不同的屏幕尺寸上保持响应式布局。
评论已关闭