美文网首页
Flutter 命名路由、路由传值、替换路由、返回根路由

Flutter 命名路由、路由传值、替换路由、返回根路由

作者: 浩仔_Boy | 来源:发表于2020-11-20 17:16 被阅读0次

main.dart

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

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

//自定组件就是类
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      onGenerateRoute: onGenerateRoute,
    );
  }
}

tabs.dart

import 'package:flutter/material.dart';
import '../bottompage/homePage.dart';
import '../bottompage/recommendPage.dart';
import '../bottompage/personalPage.dart';

/*
 * 底部tab抽离
 */
class Tabs extends StatefulWidget {
  @override
  _TabsState createState() => _TabsState();
}

class _TabsState extends State<Tabs> {
  //选中的条目
  var _currentIndex = 0;

  //tab对应的body页面
  var _pageList = [HomePage(), RecommendPage(), PersonalPage()];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("flutter bottomNavigationBar使用"),
      ),
      body: this._pageList[this._currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        fixedColor: Colors.red,
        currentIndex: this._currentIndex,
        items: [
          BottomNavigationBarItem(label: "首页", icon: Icon(Icons.home)),
          BottomNavigationBarItem(label: "推荐", icon: Icon(Icons.recommend)),
          BottomNavigationBarItem(label: "我的", icon: Icon(Icons.person))
        ],
        onTap: (value) {
          setState(() {
            this._currentIndex = value.toInt();
          });
        },
      ),
    );
  }
}

routes.dart

import 'package:demo001/tabs/tabs.dart';
import 'package:flutter/material.dart';

import '../pages/Navigator01.dart';
import '../pages/Navigator02.dart';
import '../pages/Navigator03.dart';
import '../pages/Navigator04.dart';

/*
 * 路由配置类
 */
final routes = {
  '/': (context, {arguments}) => Tabs(),
  //无状态组件
  'navigator01': (context, {arguments}) =>
      NavigatorLessWidgetPage(arguments: arguments),

  //有状态组件
  'navigator02': (context, {arguments}) =>
      NavigatorFullWidgetPage(arguments: arguments),
  //演示替换路由
  'navigator03': (context, {arguments}) => Navigator03(),
  //演示返回根路由
  'navigator04': (context, {arguments}) => Navigator04(),
};

//固定写法
// ignore: top_level_function_literal_block
var onGenerateRoute = (RouteSettings settings) {
  // 统一处理
  final String name = settings.name;
  final Function pageContentBuilder = routes[name];
  if (pageContentBuilder != null) {
    if (settings.arguments != null) {
      final Route route = MaterialPageRoute(
          builder: (context) =>
              pageContentBuilder(context, arguments: settings.arguments));
      print(settings.arguments.toString());
      return route;
    } else {
      final Route route =
          MaterialPageRoute(builder: (context) => pageContentBuilder(context));
      return route;
    }
  }
  return null;
};

Navigator01.dart

import 'package:flutter/material.dart';

/*
 * 演示无状态组件 页面传参 
 * 
 */
class NavigatorLessWidgetPage extends StatelessWidget {
  final Object arguments;
  NavigatorLessWidgetPage({this.arguments});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('无状态组件'),
      ),
      body: Text(
          'this page name is ${arguments != null ? arguments.toString() : 'null'}'),
      floatingActionButton: FloatingActionButton(
        child: Text('返回'),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
    );
  }
}

Navigator02.dart

import 'package:demo001/data/SimpleIntentData.dart';
import 'package:flutter/material.dart';

/*
 * 有状态组件传参数
 */
class NavigatorFullWidgetPage extends StatefulWidget {
  final SimpleIntentData arguments;

  const NavigatorFullWidgetPage({Key key, this.arguments}) : super(key: key);

  @override
  _NavigatorFullWidgetPageState createState() =>
      _NavigatorFullWidgetPageState(arguments: this.arguments);
}

class _NavigatorFullWidgetPageState extends State<NavigatorFullWidgetPage> {
  SimpleIntentData arguments;
  _NavigatorFullWidgetPageState({this.arguments});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${arguments.title}'),
      ),
      body: Column(
        children: [
          Text('${arguments.description}'),
          RaisedButton(
              child: Text('演示替换路由'),
              onPressed: () {
                Navigator.of(context).pushReplacementNamed(
                    "navigator03"); //用Navigator03替换Navigator02页面
              }),
          RaisedButton(
              child: Text('演示返回替换路由'),
              onPressed: () {
                Navigator.pushNamed(context, 'navigator04');
              })
        ],
      ),
    );
  }
}

Navigator03.dart

import 'package:flutter/material.dart';

/*
 * 演示替换路由
 */
class Navigator03 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Navigator03'),
      ),
    );
  }
}

Navigator04.dart

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

/*
 * 演示返回跟路由
 */
class Navigator04 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Navigator04'),
      ),
      body: RaisedButton(
          child: Text('返回'),
          onPressed: () {
            //第一个参数表示要跳转的页面 , 第二个页面将前面所有页面置为空
            Navigator.of(context).pushAndRemoveUntil(
                new MaterialPageRoute(builder: (context) => new Tabs()),
                (route) => false);
          }),
    );
  }
}

SimpleIntentData.dart

/*
 * 展示页面传值 数据类
 */
class SimpleIntentData {
  final String title;
  final String description;

  SimpleIntentData(this.title, this.description);
}

homePage.dart

import 'package:demo001/data/SimpleIntentData.dart';
import 'package:flutter/material.dart';

/*
 * 首页
 */
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  SimpleIntentData mSimpleIntentData2 =
      new SimpleIntentData('有状态组件', "无状态组件传过来2222222");
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          RaisedButton(
              child: Text('跳转到无状态组件页面,并传值'),
              onPressed: () {
                Navigator.pushNamed(context, 'navigator01', arguments: 122222);
              }),
          RaisedButton(
              child: Text('跳转到有状态组件页面,并传值'),
              onPressed: () {
                Navigator.pushNamed(context, 'navigator02',
                    arguments: mSimpleIntentData2);
              })
        ],
      ),
    );
  }
}

personalPage.dart

import 'package:flutter/material.dart';

/*
 * 我的页面
 */
class PersonalPage extends StatefulWidget {
  @override
  _PersonalPageState createState() => _PersonalPageState();
}

class _PersonalPageState extends State<PersonalPage> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        '我的',
        style: TextStyle(fontSize: 30.0),
      ),
    );
  }
}

recommendPage.dart

import 'package:flutter/material.dart';

/*
 * 推荐页面
 */
class RecommendPage extends StatefulWidget {
  @override
  _RecommendPageState createState() => _RecommendPageState();
}

class _RecommendPageState extends State<RecommendPage> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text(
        '推荐',
        style: TextStyle(fontSize: 30.0),
      ),
    );
  }
}

相关文章

网友评论

      本文标题:Flutter 命名路由、路由传值、替换路由、返回根路由

      本文链接:https://www.haomeiwen.com/subject/ytfjiktx.html