Flutter开发中的页面跳转和传值

在Android原生开发中,页面跳转用Intent类实现

Intent intent =new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);

而在安卓原生开发中,页面传值有多种方法,常见的可以用intent、Bundle、自定义类、静态变量等等来传值。
Flutter提供了两种方法路由,分别是 Navigator.push() 以及 Navigator.pushNamed() 。ci

此文基于 Flutter版本 Channel stable,v1.9.1+hotfix.2

页面跳转

构建路由Navigator.push()

  1. Navigator.push()
    从第一个页面(FirstPage())跳转到第二个页面(SecondPage())
// Within the `FirstPage` widget
onPressed: () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondPage()),
  );
}
  1. 使用Navigator.pop()回到第一个页面(FirstPage())
// Within the SecondPage widget
onPressed: () {
  Navigator.pop(context);
}

命名路由Navigator.pushNamed()

  1. Navigator.pushNamed()
    首先需要定义一个routes
MaterialApp(
  // home: FirstPage(),
  
  // Start the app with the "/" named route. In this case, the app starts
  // on the FirstPage widget.
  initialRoute: '/',
  routes: {
    // When navigating to the "/" route, build the FirstPage widget.
    '/': (context) => FirstPage(),
    // When navigating to the "/second" route, build the SecondPage widget.
    '/second': (context) => SecondPage(),
  },
);

注意这里定义了initialRoute之后,就不能定义home'属性。应该把之前定义的home属性注释掉。initialRoute属性不能与home`共存,只能选一个。

  1. 从第一个页面(FirstPage())跳转到第二个页面(SecondPage())
// Within the `FirstPage` widget
onPressed: () {
  // Navigate to the second page using a named route.
  Navigator.pushNamed(context, '/second');
}
  1. 使用Navigator.pop()回到第一个页面(FirstPage())
// Within the SecondPage widget
onPressed: () {
  Navigator.pop(context);
}

传值跳转

构建路由Navigator.push()

  1. 首先定义需要传的值
// You can pass any object to the arguments parameter.
// In this example, create a class that contains a customizable
// title and message.
class ScreenArguments {
  final String title;
  final String message;

  ScreenArguments(this.title, this.message);
}
  1. 第二个页面(SecondPage())接受传值
// A widget that extracts the necessary arguments from the ModalRoute.
class SecondPage extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    // Extract the arguments from the current ModalRoute settings and cast
    // them as ScreenArguments.
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text(args.title),
      ),
      body: Center(
        child: Text(args.message),
      ),
    );
  }
}
  1. 从第一个页面(FirstPage())传值
onPressed: () {
    // When the user taps the button, navigate to the specific route
    // and provide the arguments as part of the RouteSettings.
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => SecondPage(),
        // Pass the arguments as part of the RouteSettings. The
        // ExtractArgumentScreen reads the arguments from these
        // settings.
        settings: RouteSettings(
          arguments: ScreenArguments(
            'Extract Arguments Screen',
            'This message is extracted in the build method.',
          ),
        ),
      ),
    );
  }

命名路由Navigator.pushNamed()

  1. 首先定义需要传的值
// You can pass any object to the arguments parameter.
// In this example, create a class that contains a customizable
// title and message.
class ScreenArguments {
  final String title;
  final String message;

  ScreenArguments(this.title, this.message);
}
  1. 其次定义一下routes
  MaterialApp(
  // Provide a function to handle named routes. Use this function to
  // identify the named route being pushed, and create the correct
  // Screen.
  onGenerateRoute: 
      (settings) {
    // If you push the PassArguments route
    if (settings.name == "/passArguments") {
      // Cast the arguments to the correct type: ScreenArguments.
      final ScreenArguments args = settings.arguments;

      // Then, extract the required data from the arguments and
      // pass the data to the correct screen.
      return MaterialPageRoute(
        builder: (context) {
          return SecondPage(
            title: args.title,
            message: args.message,
          );
        },
      );
    }
  },
);
  1. 第二个页面(SecondPage())接受传值
// A Widget that accepts the necessary arguments via the constructor.
class SecondPage extends StatelessWidget {
  final String title;
  final String message;

  // This Widget accepts the arguments as constructor parameters. It does not
  // extract the arguments from the ModalRoute.
  //
  // The arguments are extracted by the onGenerateRoute function provided to the
  // MaterialApp widget.
  const SecondPage({
    Key key,
    @required this.title,
    @required this.message,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Text(message),
      ),
    );
  }
}
  1. 从第一个页面(FirstPage())传值
onPressed: () {
  // When the user taps the button, navigate to a named route
  // and provide the arguments as an optional parameter.
  Navigator.pushNamed(
    context,
    "/passArguments",
    arguments: ScreenArguments(
      'Accept Arguments Screen',
      'This message is extracted in the onGenerateRoute function.',
    ),
  );
}

第三方插件

Fluro是Flutter路由库

添加方式

dependencies:
 fluro: "^1.5.1"

使用例子

import 'package:flutter/material.dart';
import 'app_route.dart';
import 'package:fluro/fluro.dart';

void main() {
  router.define('home/:data', handler: new Handler(
      handlerFunc: (BuildContext context, Map<String, dynamic> params) {
        return new Home(params['data'][0]);
      }));
  runApp(new Login());
}

class Login extends StatefulWidget{
  @override
  createState() => new LoginState();
}

class LoginState extends State<Login>{
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'Fluro 例子',

        home: new Scaffold(
          appBar: new AppBar(
            title: new Text("登录"),
          ),
          body: new Builder(builder: (BuildContext context) {
            return new Center(child:
            new Container(
                height: 30.0,
                color: Colors.blue,
                child:new FlatButton(
                  child: const Text('传递帐号密码'),
                  onPressed: () {
                    var bodyJson = '{"user":Manjaro,"pass":passwd123}';
                    router.navigateTo(context, '/home/$bodyJson');
                  },
                )),
            );
          }),
        ));
  }
}


class Home extends StatefulWidget{
  final String _result;
  Home(this._result);
  @override
  createState() => new HomeState();
}

class HomeState extends State<Home>{
  @override
  Widget build(BuildContext context) {
    return new Center(
        child: new Scaffold(
          appBar: new AppBar(
            title: new Text("个人主页"),
          ),
          body:new Center(child:  new Text(widget._result)),
        )
    );
  }
}

'app_route.dart'的代码:

import 'package:fluro/fluro.dart';
Router router = new Router();

<img src="https://i.loli.net/2019/11/21/xsScWX6qYb75fw9.gif" style="zoom:50%;" />

Reference

fluro
官方文档
flutter移动开发中的页面跳转和传值

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容