Flutter路由的使用及页面的跳转

1.建类及路由的设置

image.png

2.页面的跳转(不带参数)

image.png
import 'package:flutter/material.dart';

class Test1 extends StatefulWidget {
  @override
  _Test1State createState() => _Test1State();
}

class _Test1State extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body:Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              FlatButton.icon(
                  onPressed: () {
                    Navigator.pushNamed(context, "/test2");
                  },
                  icon: Icon(Icons.add_circle),
                  label: Text("跳转不带参数")),

              FlatButton.icon(
                  onPressed: () {
                    Navigator.pushNamed(context, "/test3",arguments: {
                      "data":"跳转带参数的界面,拿到了数据"
                    });
                  },
                  icon: Icon(Icons.add_circle),
                  label: Text("跳转带参数的界面")),
            ],
          ),
        )
    );
  }
}
Navigator.pushNamed(context, "/test2");
Navigator.pushNamed是跳转不携带参数的跳转,/test2需要先在路由里面设置
Navigator.pushNamed(context, "/test3",arguments: { }); },是跳转携带参数的跳转,/test3需要先在路由里面设置,arguments里面是一个Map类型的数据
image.png
import 'package:flutter/material.dart';

class Test2 extends StatefulWidget {
  @override
  _Test2State createState() => _Test2State();
}

class _Test2State extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
          child:
          Text("我没携带数据,数据写死的")
      ),
    );
  }
}
image.png
import 'package:flutter/material.dart';

class Test3 extends StatefulWidget {
  @override
  _Test3State createState() => _Test3State();
}

class _Test3State extends State {
  @override
  Widget build(BuildContext context) {
    Map arguments = ModalRoute.of(context).settings.arguments;
    return Scaffold(
      body: Center(
        child: Text(arguments["data"]),
      ),
    );
  }
}
当有参数传递过来时,用ModalRoute.of(context).settings.arguments;进行接收,得到一个Map类型的数据,然后直接取Map里面的值。

main里面的代码

这里注意需要手动导包,然后才能拿到Test1()这些实例。
import 'package:flutter/material.dart';
import 'package:flutter_first/pages/Test1.dart';
import 'package:flutter_first/pages/Test2.dart';
import 'package:flutter_first/pages/Test3.dart';

void main() => runApp(MaterialApp(
      initialRoute: '/',
      routes: {
        "/": (context) => Test1(),
        "/test2": (context) => Test2(),
        "/test3": (context) => Test3()
      },
    ));

你可能感兴趣的:(Flutter路由的使用及页面的跳转)