Flutter開發(fā)中的頁面跳轉(zhuǎn)和傳值

在Android原生開發(fā)中,頁面跳轉(zhuǎn)用Intent類實現(xiàn)

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

而在安卓原生開發(fā)中,頁面?zhèn)髦涤卸喾N方法劣摇,常見的可以用intent珠移、Bundle、自定義類末融、靜態(tài)變量等等來傳值钧惧。
Flutter提供了兩種方法路由,分別是 Navigator.push() 以及 Navigator.pushNamed() 勾习。ci

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

頁面跳轉(zhuǎn)

構(gòu)建路由Navigator.push()

  1. Navigator.push()
    從第一個頁面(FirstPage())跳轉(zhuǎn)到第二個頁面(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'屬性巧婶。應(yīng)該把之前定義的home屬性注釋掉乾颁。initialRoute屬性不能與home`共存,只能選一個艺栈。

  1. 從第一個頁面(FirstPage())跳轉(zhuǎn)到第二個頁面(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);
}

傳值跳轉(zhuǎn)

構(gòu)建路由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移動開發(fā)中的頁面跳轉(zhuǎn)和傳值

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末英岭,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子湿右,更是在濱河造成了極大的恐慌诅妹,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件毅人,死亡現(xiàn)場離奇詭異吭狡,居然都是意外死亡,警方通過查閱死者的電腦和手機丈莺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進店門划煮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人缔俄,你說我怎么就攤上這事般此◎秸剑” “怎么了?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵铐懊,是天一觀的道長邀桑。 經(jīng)常有香客問我,道長科乎,這世上最難降的妖魔是什么壁畸? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮茅茂,結(jié)果婚禮上捏萍,老公的妹妹穿的比我還像新娘。我一直安慰自己空闲,他們只是感情好令杈,可當(dāng)我...
    茶點故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著碴倾,像睡著了一般逗噩。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上跌榔,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天异雁,我揣著相機與錄音,去河邊找鬼僧须。 笑死纲刀,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的担平。 我是一名探鬼主播示绊,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼暂论!你這毒婦竟也來了耻台?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤空另,失蹤者是張志新(化名)和其女友劉穎盆耽,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體扼菠,經(jīng)...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡摄杂,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了循榆。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片析恢。...
    茶點故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖秧饮,靈堂內(nèi)的尸體忽然破棺而出映挂,到底是詐尸還是另有隱情泽篮,我是刑警寧澤,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布柑船,位于F島的核電站帽撑,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏鞍时。R本人自食惡果不足惜亏拉,卻給世界環(huán)境...
    茶點故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望逆巍。 院中可真熱鬧及塘,春花似錦、人聲如沸锐极。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽灵再。三九已至肋层,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間檬嘀,已是汗流浹背槽驶。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工责嚷, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留鸳兽,地道東北人。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓罕拂,卻偏偏與公主長得像揍异,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子爆班,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,442評論 2 359

推薦閱讀更多精彩內(nèi)容