严格来说,BLoC(Business Logic Component)不是一个技术知识点,而是一种业务与界面分离的思想,类似于MVC MVP等。
实现思想
- 定义一个BloC类,内部定义业务数据,使用StreamController,对外暴露stream和sink。
- 利用StreamBuilder包裹真正使用数据的widget,builder会持续返回更新数据。
简单示例
import 'dart:async';
import 'package:flutter/material.dart';
class BlocTest extends StatefulWidget {
@override
_BlocTestState createState() => _BlocTestState();
}
class _BlocTestState extends State<BlocTest> {
PageTestBloc ptb = PageTestBloc();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("BLoC"),
centerTitle: true,
),
body: Center(
child: StreamBuilder(
stream: ptb.stream,
builder: (context,AsyncSnapshot<int> snapshot){
return Text(snapshot.data.toString());
},
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: (){
ptb.add();
},
),
);
}
}
class PageTestBloc {
int _count = 0;
StreamController<int> _controller = StreamController<int>();
StreamSink<int> get _sink => _controller.sink;
Stream<int> get stream => _controller.stream;
void dispose(){
_controller.close();
}
void add(){
_count++;
_sink.add(_count);
}
}
网友评论