點燈坊

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

Navigator.push() 跳轉頁面

Sam Xiao's Avatar 2024-11-29

Navigator.push() 可直接跳轉到指定頁面。

Version

Flutter 3.24.5

Flutter

overview01

  • Android 與 iOS 都成功使用 Navigator.push() 跳轉頁面

page_a.dart

import 'package:flutter/material.dart';
import 'package:flutter_lab/page_b.dart';

class PageA extends StatefulWidget {
  const PageA({super.key});

  
  State<PageA> createState() => _PageA();
}

class _PageA extends State<PageA> {
  
  Widget build(BuildContext context) {
    var appBar = AppBar(
      title: const Text(
        'Page A',
      ),
    );

    var floatingActionButton = FloatingActionButton(
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => PageB(),
          ),
        );
      },
      child: const Icon(
        Icons.navigate_next,
      ),
    );

    var body = Center(
      child: Text(
        'Page A',
      ),
    );

    return Scaffold(
      appBar: appBar,
      floatingActionButton: floatingActionButton,
      body: body,
    );
  }
}

Line 20

var floatingActionButton = FloatingActionButton(
  onPressed: () {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PageB(),
      ),
    );
  },
  child: const Icon(
    Icons.navigate_next,
  ),
);
  • Navigator.push():跳轉到其他頁面
    • MaterialPageRoute:將 View 包成 Route
      • builder():指定要跳轉的 View

page_b.dart

import 'package:flutter/material.dart';

class PageB extends StatefulWidget {
  const PageB({super.key});

  
  State<PageB> createState() => _PageB();
}

class _PageB extends State<PageB> {
  
  Widget build(BuildContext context) {
    var appBar = AppBar(
      title: const Text(
        'Page B',
      ),
    );

    var body = Center(
      child: Text(
        'Page B',
      ),
    );

    return Scaffold(
      appBar: appBar,
      body: body,
    );
  }
}
  • 一般正常的 View

Conclusion

  • Navigator.push() 不必事先定義好 Route,只要直接指定要跳轉的 View 即可