在 Flutter 中使用服务定位器管理路由
问题
在 Flutter 中进行页面跳转需要访问到当前的 BuildContext
及目标页面的 Widget
,不利于代码的组织管理。
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
}
服务定位器(Service Locator)
The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the “service locator”, which on request returns the information necessary to perform a certain task. Proponents of the pattern say the approach simplifies component-based applications where all dependencies are cleanly listed at the beginning of the whole application design, consequently making traditional dependency injection a more complex way of connecting objects. Critics of the pattern argue that it is an anti-pattern which obscures dependencies and makes software harder to test.
简单来说服务定位器模式可以将获得服务的过程封装在服务定位器中,应用程序的代码不需要管理维护服务的大量依赖,使应用程序的结构得到良好的分离。