Flutter路由的几种用法小结

来自:网络
时间:2024-06-09
阅读:

Flutter路由跳转

基本路由跳转 

ElevatedButton(
  onPressed: () {
    //基本路由跳转
    Navigator.of(context).push(
      MaterialPageRoute(builder: (BuildContext context) {
        return const SearchPage();
      }),
    );
  },
  child: const Text("基本路由跳转"),
),

search.dart页面

import 'package:flutter/material.dart';
class SearchPage extends StatefulWidget {
  final String context;
  final int aid;
  const SearchPage({
    super.key,
    this.context = "",
    this.aid = 0,
  });
  @override
  State<SearchPage> createState() => _SearchPageStateState();
}
class _SearchPageStateState extends State<SearchPage> {
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //返回到上一页路由
          Navigator.pop(context);
        },
        child: const Icon(Icons.close),
      ),
      appBar: AppBar(
        title: const Text("搜索页面"),
      ),
      body: Center(
        child: Text(
          "${widget.context} "
          "${widget.aid == 0 ? "" : ",代号:${widget.aid}"}"
        ),
      ),
    );
  }
}

返回上一页路由

Navigator.pop(context);

基本路由跳转传参

ElevatedButton(
  onPressed: () {
    //基本路由跳转传参
    Navigator.of(context).push(
      MaterialPageRoute(builder: (BuildContext context) {
        return const SearchPage(
            context: "首页传过来的参数", aid: 123456);
      }),
    );
  },
  child: const Text("基本路由跳转传参"),
),

命名路由跳转

ElevatedButton(
  onPressed: () {
    //命名路由跳转
    Navigator.pushNamed(context, "/search");
  },
  child: const Text("命名路由跳转"),
),

命名路由跳转需要先配置路由

routers.dart配置文件

import 'package:flutter/material.dart';
import 'package:flutter_demo/form.dart';
import 'package:flutter_demo/register2.dart';
import 'package:flutter_demo/search.dart';
//配置路由
Map routes = {
  "/search": (context) => const SearchPage(),
  "/register2": (context) => const Register2(),
  "/form": (context, {arguments}) => FormPage(arguments: arguments),
};
//配置onGenerateRoute固定写法,这个方法相当于一个中间件,可以做权限判断
var onGenerateRoute = (RouteSettings settings) {
  final String? name = settings.name;
  final Function? pageContentBuilder = routes[name];
  if (pageContentBuilder != null) {
    if (settings.arguments != null) {
      final Route route = MaterialPageRoute(
        builder: (context) =>
            pageContentBuilder(context, arguments: settings.arguments),
      );
      return route;
    } else {
      final Route route = MaterialPageRoute(
        builder: (context) => pageContentBuilder(context),
      );
      return route;
    }
  }
  return null;
};

然后需要在首页添加initialRoute和onGenerateRoute配置

import 'package:flutter_demo/routers/routers.dart';
void main() {
  runApp(const MyApp());
}
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //隐藏DEBUG图标
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const Scaffold(
        body: MyHomePage(),
      ),
      initialRoute: "/",
      onGenerateRoute: onGenerateRoute,
    );
  }
}

命名路由跳转传参

ElevatedButton(
  onPressed: () {
    //命名路由传参
    Navigator.pushNamed(
      context,
      "/form",
      arguments: {
        "aid": 123456,
        "name": "张三",
        "age": "18",
      },
    );
  },
  child: const Text("命名路由传参"),
),

context属性中写配置中的路径,arguments属性中是跳转需要带的参数,跳转到form.dart页面并接收参数。

import 'package:flutter/material.dart';
class FormPage extends StatefulWidget {
  final Map arguments;
  const FormPage({
    super.key,
    required this.arguments,
  });
  @override
  State<FormPage> createState() => _FormPageStateState();
}
class _FormPageStateState extends State<FormPage> {
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("表单页面"),
      ),
      body: Center(
        child: Text(
          widget.arguments.isEmpty
              ? ""
              : "我是${widget.arguments["name"]},我${widget.arguments["age"]}了,"
                  "代号:${widget.arguments["aid"]}",
        ),
      ),
    );
  }
}

命名路由替换跳转

Navigator.of(context).pushReplacementNamed("/register2");

命名路由替换跳转用pushReplacementNamed,跳转新页面后本页面被替换掉。

移除所有页面返回到根页面

Navigator.of(context).pushAndRemoveUntil(
    MaterialPageRoute(builder: (BuildContext context) {
  return const MyApp();
}), (route) => false);

移除所有页面并返回到指定页面用pushAndRemoveUntil。

返回顶部
顶部