Strictly speaking, BLoC (Business Logic Component) is not a technical point of knowledge, but an idea of separating Business from interface, similar to MVC MVP, etc.

Implement ideas
  • Define a BloC class, internally define business data, use StreamController, externally expose stream and sink.
  • With StreamBuilder wrapped around widgets that actually use data, the Builder continually returns updated data.
  • StreamBuilder keeps track of the latest data in the stream and automatically calls the Build method to rerender the component when the stream changes.
A simple example
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); }}Copy the code

Note that the local refresh is here: