接下来,我们通过脚手架设置一个页面吧!
基础代码
第一个页面我们通过脚手架可以实现业务逻辑与视图实现分离,添加两个文件
./lib/src/page/index_page.dart
import 'package:base_plugin/base_plugin.dart';
import 'package:flutter/material.dart';
class IndexPage extends StatefulWidget {
const IndexPage({Key key}) : super(key: key);
@override
_IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage>
with PagePresenter<IndexPage, IndexProvider> {
@override
Widget get buildWidget => Scaffold(
appBar: AppBar(
title: Text('示例工程'),
),
body: Text(provider.msg),
);
}
./lib/src/page/index_provider.dart
class IndexProvider extends BaseProvider {
String msg = "Hello World";
@override
Future get dataFuture => null; // 需要加载数据的Future
}
如代码所示,我们只需要 with(混入)一个PagePresenter 即可实现代码逻辑分离,然后将两者关联起来,视图侧我们使用provider这个变量即可获取关联的逻辑侧实例
声明路由
一开始我们使用了r_router 声明的路由,我们现在开始使用脚手架声明的方式,即可在视图侧识别provider
修改 ./lib/main.dart 的初始化配置改为
Routes().addPRouter<IndexProvider>(
path: '/',
handler: (ctx) => IndexPage(),
providerBuilder: (ctx) => IndexProvider());
实现经典点击计数
当点击加号按钮时,文字计数+1,修改index_page 和 index_provider 如下
// index_page.dart
@override
Widget get buildWidget => Scaffold(
appBar: AppBar(
title: const Text('示例工程'),
),
body: Center(
child: dataSelector<int>(
selector: (__, _) => _.count,
builder: (BuildContext context, int value, Widget? child) => Text(
'您当前已点击\n$value',
textAlign: TextAlign.center,
),
)),
floatingActionButton: FloatingActionButton(
onPressed: provider.onAdd,
child: const Icon(Icons.add),
),
);
// index_provider
class IndexProvider extends BaseProvider {
int count = 0;
@override
Future? get dataFuture => null;
@override
void initState() {
super.initState();
}
void onAdd() {
count +=1;
update();
}
}
可以看到我们使用dataSelector 监听count 变量的改变,当点击按钮时,触发计数和update() , 并实现了局部刷新,使良好而流畅的开发体验持续上升,视图与逻辑分离但又紧密的联系在一起,这种若即若离的感觉在后续该教程的学习会越来越明显。
暂无评论内容