关于flutter:flutter-fluro-优化路由配置

53次阅读

共计 2026 个字符,预计需要花费 6 分钟才能阅读完成。

问题:
谬误页面如何解决?带参数的页面如何解决?
步骤:
1、谬误页面解决

①在 /page 目录增加 not_found.dart    
②实现 NotFoundPage    
③在 router.dart 增加_notFoundHandler  
④在 router.dart 的 configureRoutes 中增加 router.notFoundHandler=_notFoundHandler  
⑤批改 PageContent 测试  

2、带参数的页面解决

①在 /page 目录增加 room_detail/index.dart  
②实现 RoomDetailPage    
③在 router.dart 增加_RoomDetailHandler  
④在 router.dart 的 configureRoutes 中增加 router.RoomDetailHandler=_RoomDetailHandler  
⑤批改 PageContent 测试  

not_found.dart

import 'package:flutter/material.dart';

class NotFoundPage extends StatelessWidget {const NotFoundPage({ Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title: Text('404'),),
      body: Center(child: Text('您拜访的页面不存在')),
    );
  }
}

room_detail/index.dart

import 'package:flutter/material.dart';

class RoomDetailPage extends StatelessWidget {
  final String roomId;

  const RoomDetailPage({Key key, this.roomId}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title: Text('roomId: $roomId'),),
    );
  }
}

router.dart

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import './pages/room_detail/index.dart';
import './pages/not_found.dart';
import './pages/home/index.dart';
import './pages/login.dart';

class Routes {
  //1、定义路由名称
  static String home = '/';
  static String login = '/login';
  static String roomdetail = '/room/:roomId';
  //2、定义路由处理函数
  static Handler _homeHandler = Handler(handlerFunc: (BuildContext context, Map<String, dynamic> params) {return HomePage();
  });

  static Handler _loginHandler = Handler(handlerFunc: (BuildContext context, Map<String, dynamic> params) {return LoginPage();
  });

  static Handler _roomDetailHandler = Handler(handlerFunc: (BuildContext context, Map<String, dynamic> params) {return RoomDetailPage(roomId: params['roomId'][0],);
  });

  static Handler _NotFoundHandler = Handler(handlerFunc: (BuildContext context, Map<String, dynamic> params) {return NotFoundPage();
  });

  //3、编写函数 configureRoutes 关联路由名称和处理函数
  static void configureRoutes(FluroRouter router) {router.define(home, handler: _homeHandler);
    router.define(login, handler: _loginHandler);
    router.define(roomdetail, handler: _roomDetailHandler);
    router.notFoundHandler = _NotFoundHandler;
  }

}

成果如下:

正文完
 0