非常感谢vbandrade,他的回答帮助我弄清楚了。与我合作的解决方案是:
StreamController如果需要
sink在我的
bloc业务逻辑组件中侦听a ,然后
stream将其输出到其他元素,则需要2 。
该
counter_bloc.dart是:
import 'dart:async';class CounterBloc { int _count = 0; // The controller to stream the final output to the required StreamBuilder final _counter = StreamController.broadcast<int>(); Stream<int> get counter => _counter.stream; // The controller to receive the input form the app elements final _query = StreamController<int>(); Sink<int> get query => _query.sink; Stream<int> get result => _query.stream; // The business logic CounterBloc() { result.listen((increment) { // Listen for incoming input _count += increment; // Process the required data _counter.add(_count); // Stream the required output }); } void dispose(){ _query.close(); _counter.close(); }}并且
main.dart是:
import 'counter_bloc.dart';import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); }}class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override State<StatefulWidget> createState() { return _MyHomePageState(); }}class _MyHomePageState extends State<MyHomePage> { var bloc = CounterBloc(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), StreamBuilder<int>( // Listen to the final output sent from the Bloc stream: bloc.counter, initialdata: 0, builder: (BuildContext c, AsyncSnapshot<int> data) { return Text( '${data.data}', style: Theme.of(context).textTheme.display1, ); }, ), ], ), ), floatingActionButton: Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ FloatingActionButton( onPressed: () { bloc.query.add(2); // Send input to the Bloc }, tooltip: 'Increment 2', child: Text("+2"), ), FloatingActionButton( onPressed: () { bloc.query.add(1); // Send input to the Bloc }, tooltip: 'Increment 1', child: Text("+1"), ), ], ), // This trailing comma makes auto-formatting nicer for build methods. ); }}


