NavigationBar
所切換的每個 Page,實務上由於會非常複雜,會將每個 Page 抽出成獨立檔案。
Version
Flutter 3.24
Flutter
NavigationBar
navigation.dart
import 'package:flutter/material.dart';
import 'home.dart';
import 'profile.dart';
import 'search.dart';
class Navigation extends StatefulWidget {
const Navigation({super.key});
State<Navigation> createState() => _Navigation();
}
class _Navigation extends State<Navigation> {
int _selectedIndex = 0;
static List<Widget> navigationPages = [
const Home(),
const Search(),
const Profile(),
];
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('NavigationBar'),
);
var navigationBar = NavigationBar(
selectedIndex: _selectedIndex,
onDestinationSelected: (int index) =>
setState(() => _selectedIndex = index),
destinations: const [
NavigationDestination(
icon: Icon(Icons.home),
label: 'Home',
),
NavigationDestination(
icon: Icon(Icons.search),
label: 'Search',
),
NavigationDestination(
icon: Icon(Icons.person),
label: 'Profile',
),
],
);
return Scaffold(
appBar: appBar,
body: navigationPages[_selectedIndex],
bottomNavigationBar: navigationBar,
);
}
}
Line 17
static List<Widget> navigationPages = [
const Home(),
const Search(),
const Profile(),
];
navigationPages
:定義每個NavigationButton
所對應的 page
Line 3
import 'home.dart';
import 'profile.dart';
import 'search.dart';
Home
、Profile
與Search
都來自獨立的外部檔案
home.dart
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
const Home({super.key});
Widget build(BuildContext context) {
return const Center(
child: Text('Home Page'),
);
}
}
Home
可繼承自StatelessWidget
或StatefulWidget
build()
:一樣在build()
內實現 UI 部分
Conclusion
- 可是需求把一部分 UI 拆到獨立的檔案,並不一定得將所有 UI 寫在同一個檔案