Flutter

Flutter 2.0的路由把我搞懵了

2021-12-10  本文已影响0人  岛上码农

前言

前面几篇介绍了 Flutter 的路由,包括使用自带的 Navigator 和使用 fluro 路由插件,实际上两种方式都能满足日常开发的使用。但是,如果你上 Flutter 的官网,就会发现关于路由,有这么一段内容:

To learn about Flutter’s original (1.0) navigation and routing mechanism, see the Navigation recipes in the Flutter cookbook and the Navigator API docs. The original navigation model uses an imperative approach.
To learn about Flutter’s updated (2.0) navigation and routing mechanism, which uses a declarative approach, see Learning Flutter’s new navigation and routing system.
Note that this new mechanism isn’t a breaking change—you can continue to use the original approach if that serves you well. If you want to implement deep linking, or take advantage of multiple navigators, check out the 2.0 version.

意思是你使用1.0的路由也没什么问题,不会受版本升级影响,但是如果想实现深度的链接(应该是指多层级),或者多导航器的特性,那么就可以考虑2.0版本的路由。

Flutter 2.0的路由是个啥?

Flutter 2.0的路由相比1.0来说多了很多东西,一时半会闹不明白。


image.png

总的来说,为了实现高大上的路由,多了下面这些东西:

看上面的描述完全不知道具体怎么回事,感觉搞得太复杂了,让人望而生畏啊!


image.png

具体机制

还好,配了张图,关系总算能够理得顺了。


image.png

举个例子:


image.png
  1. 假设需要导向新的路由,例如 books/2RouteInformationParser 会将其转换为一个应用中定义的抽象的数据类型 T,例如一个名叫 BooksRoutePath 的类。
  2. RouterDelegate 会调用其 setNewRoutePath 方法,并将这个类作为它的参数,并且必须更新应用的状态以便反映这些变化(例如设置 selectedBooKId)并且调用 notifyListeners
  3. notifyListeners 被调用后,它会通知 Router 重建 RouterDelegate(通过调用其build方法)。
  4. RouterDelegate.builder()返回一个新的导航器,导航器的页面反映了 app 状态的变化(例如 selectedBookId)。

感觉还是有点费解,而且还引入了BooksRoutePath这个自定义的类,来个时序图看一下。

2.0路由时序图

有了这张图会更清晰一些,其实和之前1.0的路由有点相似,都是解析路由,然后找到匹配页面再显示。只是这套机制更为复杂,实际需要通过代码才能了解具体实现方式,下一篇再上demo。

上一篇 下一篇

猜你喜欢

热点阅读