匿名路由

核心代码:

Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => ShopPage())
);
import 'package:flutter/material.dart';

class BasicPage extends StatelessWidget {
  const BasicPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => ShopPage())
            );
          },
          child: Text("跳转到商品页面"),
        ),
      ),
    );
  }
}

class ShopPage extends StatelessWidget {
  const ShopPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: ElevatedButton(
          onPressed: () => Navigator.pop(context),
          child: Text("返回"),
        ),
      ),
    );
  }
}

命名路由

根据路由名字push到对应的地方

核心配置:

Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        "home": (context) => BasicPage(),
        "shop": (context) => ShopPage()
      },
      initialRoute: "home",
      // home: BasicPage(),
    );
  }
Navigator.pushNamed(
  context,
  "shop"
);