點燈坊

失くすものさえない今が強くなるチャンスよ

NavigationBar 支援每個 Page 獨立檔案

Sam Xiao's Avatar 2024-10-29

NavigationBar 所切換的每個 Page,實務上由於會非常複雜,會將每個 Page 抽出成獨立檔案。

Version

Flutter 3.24

Flutter

navigationbar01

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';
  • HomeProfileSearch 都來自獨立的外部檔案

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 可繼承自 StatelessWidgetStatefulWidget
  • build() :一樣在 build() 內實現 UI 部分

Conclusion

  • 可是需求把一部分 UI 拆到獨立的檔案,並不一定得將所有 UI 寫在同一個檔案