如何处置Stream Controller Flutter

时间:2019-07-07 10:37:56

标签: flutter dart

我正在使用基本的Bloc模式测试如何使用流和流控制器,但是我仍然不知道如何正确处理它们是使用它来更新UI还是触发其他集团。

我注意到其他人的代码将它们处理在无状态或有状态的小部件上,但是我想知道是否也可以在Bloc类上完成它

下面是基本Bloc和无状态小部件的流构建器的代码段

CounterBloc.dart

import 'dart:async';

class CounterBloc {
  int _counter = 10;
  StreamController<int> _countController = StreamController<int>();

  Stream<int> get counterStream => _countController.stream;
  StreamSink<int> get counterSink => _countController.sink;

  void increamentCounter() {
    _counter++;
    counterSink.add(_counter);
  }
}

main.dart

import 'package:flutter/material.dart';
import 'package:test_bloc/counter_bloc.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(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final counterClass = CounterBloc();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Home Page"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'You have pushed the button this many times:',
              ),
              StreamBuilder(
                stream: counterClass.counterStream,
                builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                  if (snapshot.hasData) {
                    print(snapshot.data.toString() + ' this is test');
                    return Text(snapshot.data.toString());
                  } else {
                    return CircularProgressIndicator();
                  }
                },
              )
            ],
          ),
        ),
        floatingActionButton: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            FloatingActionButton(
              onPressed: () {
                counterClass.increamentCounter();
              },
              tooltip: 'Increment',
              child: Icon(Icons.add),
            )
          ],
        ));
  }
}

1 个答案:

答案 0 :(得分:2)

您可能想在closeStream类中创建一个名为Bloc的方法。

void closeStream() {
  _countController.close();
}

HomePage转换为StatefulWidget,覆盖dispose()方法,然后使用

@override
void dispose() {
  counterClass.closeStream();
  super.dispose();
}