天天看點

Flutter學習-命名路由

命名路由+參數傳遞

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '命名路由',
      initialRoute: '/', //應用首頁
      routes: {
        //注冊路由表
        '/': (context) => NamedRoute(),
        'second_page': (context) => SecondPage(),
        'third_page': (context) {
          return ThirdPage(
            text: ModalRoute.of(context).settings.arguments,    //傳參配置
          );
        }
      },
    );
  }
}

class NamedRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('命名路由demo'),
        ),
        body: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('toSecondPage'),
              onPressed: () {
                Navigator.pushNamed(context, 'second_page', arguments: '傳值成功'); //命名路由跳轉、傳值
              },
            ),
            RaisedButton(
              child: Text('toThirdPage'),
              onPressed: () async { //異步函數
                var result = await Navigator.pushNamed(context, 'third_page',
                    arguments: '傳值給第三頁面');
                print('傳回值:$result');   //列印傳回值
              },
            )
          ],
        )));
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var args = ModalRoute.of(context).settings.arguments;   //接收傳過來的參數
    return Scaffold(
      appBar: AppBar(
        title: Text('SecondPage'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[Text('路由2'), Text(args)],
        ),
      ),
    );
  }
}

class ThirdPage extends StatelessWidget {
  ThirdPage({Key key, @required this.text}) : super(key: key);  //接收參數
  final String text;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Third Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(text),
            RaisedButton(
              onPressed: () => Navigator.pop(context, '我是傳回值'),
              child: Text('傳回'),
            )
          ],
        ),
      ),
    );
  }
}
           

運作效果:

Flutter學習-命名路由
Flutter學習-命名路由
Flutter學習-命名路由