flutter路由跳转

时间:2024-03-26 08:40:48

Navigator.of(context).push(); //路由跳转(模块方式)

Navigator.of(context).push(MaterialPageRoute(
              builder: (BuildContext context) {
                return const Page() ;//Page()指页面
              },
))

Navigator.pushNamed(context, "/") //路由跳转(路由方式)

Navigator.pop(context)//返回上级

路由对象  widget

获取/使用路由参数 (widget.id / widget.title)     使用${widget.title}

1.基本路由

button按钮点击跳转示例(传参)

//button按钮点击事件  
//在button页面内引入Page 
//import './page.dart';
IconButton(
	onPressed: () => {
			Navigator.of(context).push(
				MaterialPageRoute(builder: (BuildContext context)=>const PageWidget(title:'小刀刀',id:12);)
			)
		 },
    icon: const Icon(Icons.keyboard_arrow_right), //设置图标
)

//page页面
import 'package:flutter/material.dart';

class PageWidget extends StatefulWidget {
  final String title;
  final int id;
  const PageWidget({super.key, this.title = "我是系统设置", required this.id});
  @override
  State<PageWidget> createState() => _PageWidgetState();
}

class _PageWidgetState extends State<PageWidget> {
  String str = '';
  @override
  void initState() {
    super.initState();
    //根据传递的id参数, 格式化数据
    str = "传递参数为${widget.id}";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => Navigator.pop(context),
        child: const Icon(Icons.arrow_left_outlined),
      ),
      appBar: AppBar(
        title: const Text("路由传参"),
        centerTitle: true,
      ),
      body: Center(
          child: Text("${widget.title}:$str",
              style: const TextStyle(color: Colors.pink))),
    );
  }
}

2.命名路由-不携带参数

Navigator.pushNamed(context, "/") //路由跳转(路由方式)

在main.dart的MaterialApp的routes中配置整体路由 格式routes:{key:()=>Widget(),....}

initialRoute默认路由

//main.dart
void main() {
  runApp(MaterialApp(title: 'contaniner', initialRoute: "/", routes: {
      "/": (context) => const HomeWidget(),
      "/page": (context) => const PageWidget(),
    }));
}

//home.dart

import 'package:flutter/material.dart';

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

  @override
  State<HomeWidget> createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("首页"),
        centerTitle: true,
      ),
      body: ElevatedButton(
        onPressed: () => Navigator.pushNamed(context, "/page"),
        child: const Text("我是命名路由"),
      ),
    );
  }
}

//page页面
import 'package:flutter/material.dart';

class PageWidget extends StatefulWidget {
  const PageWidget({super.key});
  @override
  State<PageWidget> createState() => _PageWidgetState();
}

class _PageWidgetState extends State<PageWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => Navigator.pop(context),
        child: const Icon(Icons.arrow_left_outlined),
      ),
      appBar: AppBar(
        title: const Text("命名路由"),
        centerTitle: true,
      ),
      body: Center(
          child: Text("我是Page页面")),
    );
  }
}

3.命名路由-传参

注意点:

A.创建路由Map

B.main.dart的MaterialApp添加onGenerateRoute

C.接收使用参数:

final Map arguments;

const PageWidget({super.key, required this.arguments });

print(widget.arguments);

//main.dart
import 'package:flutter/material.dart';
import './router/page.dart';
import './router/home.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    final Map _routerMap = {
      "/": (context) => HomeWidget(),
      "/page": (context, {arguments}) => PageWidget(arguments: arguments),
    };
    return MaterialApp(
      title: 'contaniner',
      initialRoute: "/",
      onGenerateRoute: (RouteSettings settings) {
        //settings.name 路由地址
        //settings.arguments  携带参数
        // 统一处理
        final String? name = settings.name;
        final Function? pageContentBuilder = _routerMap[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;
      },
    );
  }
}

//home.dart

import 'package:flutter/material.dart';

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

  @override
  State<HomeWidget> createState() => _HomeWidgetState();
}

class _HomeWidgetState extends State<HomeWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("首页"),
        centerTitle: true,
      ),
      body: ElevatedButton(
        onPressed: () => Navigator.pushNamed(context, "/page",
            arguments: {"title": '我是命名路由传值', "id": 20}),
        child: const Text("我是命名路由传参"), //设置图标
      ),
    );
  }
}




//page.dart
import 'package:flutter/material.dart';

class PageWidget extends StatefulWidget {
  //接收参数
  final Map arguments;
  const PageWidget({super.key, required this.arguments });
  @override
  State<PageWidget> createState() => _PageWidgetState();
}

class _PageWidgetState extends State<PageWidget> {
 
  @override
  void initState() {
    super.initState();
    // str = "传递参数为${widget.id}";
    print(widget.arguments);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => Navigator.pop(context),
        child: const Icon(Icons.arrow_left_outlined),
      ),
      appBar: AppBar(
        title: const Text("Page页面"),
        centerTitle: true,
      ),
      body:  Text("${widget.arguments}"),
    );
  }
}