bloc_base.dart文件用来强制销毁stream
abstract class BlocBase { void dispose(); }bloc_counter.dart实例化StreamController,同时实现两个方法,内部方法_counter往流里面塞内容,外部方法counter往外“吐”出内容:
import 'dart:async'; import 'bloc_base.dart'; class BlocCounter extends BlocBase { final _controller = StreamController<int>(); get _counter => _controller.sink; get counter => _controller.stream; void increment(int count) { _counter.add(++count); } @override void dispose() { _controller.close(); } }main.dart调用bloc_counter的外部方法,往流里面塞内容:
import 'package:flutter/material.dart'; import 'bloc_counter.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'bloc示例', home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(BlocCounter()); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; final BlocCounter bloc; _MyHomePageState(this.bloc); void _incrementCounter() { bloc.increment(_counter); } @override void initState() { bloc.counter.listen((_count) { setState(() { _counter = _count; }); }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('StreamBuilder示例'), ), body: Center( child: Text( '$_counter', // ignore: deprecated_member_use style: Theme.of(context).textTheme.display1, ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, child: Icon(Icons.add), ), ); } @override void dispose() { super.dispose(); } }