我使用RxDart来观察变化并相应地更新UI.当应用程序启动时,我正在进行网络通话并成功获取数据,观察更改并相应更新UI.但当我在关闭屏幕时处理Subjects.它给出了以下错误:

══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (15524): The following StateError was thrown while finalizing the widget tree:
I/flutter (15524): Bad state: You cannot close the subject while items are being added from addStream

下面是BLOC类:

class MovieDetailBloc {
  final _repository = Repository();
  final _movieId = PublishSubject<int>();
  final _trailers = BehaviorSubject<Future<TrailerModel>>();

  Function(int) get fetchTrailersById => _movieId.sink.add;
  Observable<Future<TrailerModel>> get movieTrailers => _trailers.stream;

  MovieDetailBloc() {
    _movieId.stream.transform(_itemTransformer()).pipe(_trailers);
  }

  dispose() {
    _movieId.close();
    _trailers.close();
  }

  _itemTransformer() {
    return ScanStreamTransformer(
      (Future<TrailerModel> trailer, int id, int index) {
        print(index);
        trailer = _repository.fetchTrailers(id);
        return trailer;
      },
    );
  }
}

这是我正在调用的UI屏幕:

import 'dart:async';

import 'package:flutter/material.dart';
import '../blocs/movie_detail_bloc_provider.dart';
import '../models/trailer_model.dart';

class MovieDetail extends StatefulWidget {
  final posterUrl;
  final description;
  final releaseDate;
  final String title;
  final String voteAverage;
  final int movieId;

  MovieDetail({
    this.title,
    this.posterUrl,
    this.description,
    this.releaseDate,
    this.voteAverage,
    this.movieId,
  });

  @override
  State<StatefulWidget> createState() {
    return MovieDetailState(
      title: title,
      posterUrl: posterUrl,
      description: description,
      releaseDate: releaseDate,
      voteAverage: voteAverage,
      movieId: movieId,
    );
  }
}

class MovieDetailState extends State<MovieDetail> {
  final posterUrl;
  final description;
  final releaseDate;
  final String title;
  final String voteAverage;
  final int movieId;

  MovieDetailBloc bloc;

  MovieDetailState({
    this.title,
    this.posterUrl,
    this.description,
    this.releaseDate,
    this.voteAverage,
    this.movieId,
  });

  @override
  void didChangeDependencies() {
    bloc = MovieDetailBlocProvider.of(context);
    bloc.fetchTrailersById(movieId);
    super.didChangeDependencies();

  }

  @override
  void dispose() {
    bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              expandedHeight: 220.0,
              floating: false,
              pinned: false,
              flexibleSpace: FlexibleSpaceBar(
                  background: Image.network(
                "https://image.tmdb.org/t/p/w500$posterUrl",
                fit: BoxFit.cover,
              )),
            ),
          ];
        },
        body: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(margin: EdgeInsets.only(top: 5.0)),
              Text(
                title,
                style: TextStyle(
                  fontSize: 25.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Container(margin: EdgeInsets.only(top: 8.0, bottom: 8.0)),
              Row(
                children: <Widget>[
                  Icon(
                    Icons.favorite,
                    color: Colors.red,
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 1.0, right: 1.0),
                  ),
                  Text(
                    voteAverage,
                    style: TextStyle(
                      fontSize: 18.0,
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.only(left: 10.0, right: 10.0),
                  ),
                  Text(
                    releaseDate,
                    style: TextStyle(
                      fontSize: 18.0,
                    ),
                  ),
                ],
              ),
              Container(margin: EdgeInsets.only(top: 8.0, bottom: 8.0)),
              Text(description),
              Container(margin: EdgeInsets.only(top: 8.0, bottom: 8.0)),
              Text(
                "Trailer",
                style: TextStyle(
                  fontSize: 25.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Container(margin: EdgeInsets.only(top: 8.0, bottom: 8.0)),
              StreamBuilder(
                stream: bloc.movieTrailers,
                builder:
                    (context, AsyncSnapshot<Future<TrailerModel>> snapshot) {
                  if (snapshot.hasData) {
                    return FutureBuilder(
                      future: snapshot.data,
                      builder:
                          (context, AsyncSnapshot<TrailerModel> itemSnapShot) {
                        if (itemSnapShot.hasData) {
                          if (itemSnapShot.data.results.length > 0)
                            return trailerLayout(itemSnapShot.data);
                          else
                            return noTrailer(itemSnapShot.data);
                        } else {
                          return CircularProgressIndicator();
                        }
                      },
                    );
                  } else {
                    return CircularProgressIndicator();
                  }
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget noTrailer(TrailerModel data) {
    return Center(
      child: Container(
        child: Text("No trailer available"),
      ),
    );
  }
}

Widget trailerLayout(TrailerModel data) {
  return Row(
    children: <Widget>[
      Expanded(
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(5.0),
              height: 100.0,
              color: Colors.grey,
            ),
            Text(
              data.results[0].name,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
      Expanded(
        child: Column(
          children: <Widget>[
            Container(
              margin: EdgeInsets.all(5.0),
              height: 100.0,
              color: Colors.grey,
            ),
            Text(
              data.results[1].name,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    ],
  );
}

当我关闭屏幕时,错误就出现了.dispose方法正在引发上述异常.我该如何解决这个问题?

推荐答案

我认为排水应该可以解决这个问题

  dispose() async {
    _movieId.close();
    await _trailers.drain();
    _trailers.close();
  }

https://api.dartlang.org/stable/2.0.0/dart-async/Stream-class.html

Dart相关问答推荐

有没有办法否定IF条件中的模式大小写匹配?

Dart 中的const关键字放置有什么不同?

浮动操作按钮:如何像 RaisedButton 一样更改启动 colored颜色 和突出显示 colored颜色 ?

在 Flutter 中以间隔自动获取 API 数据

Flutter Web:无法用鼠标向下滚动(drag)(Flutter 2.5+)

设置文本以匹配Flutter中的列宽

如何使我的Flitter应用程序的导航抽屉(Navigation Drawer)透明?

如何go 除字符串中的变音符号?

在Flatter中滚动列表视图时,网络图像一直消失?

在 Flutter 中推送新页面时,Navigator 堆栈上的页面会重建

Flatter BLoC-如何将参数传递给事件?

Flutter 中 ListView.builder 中的反向列表

使用 dart 下载文件

如何在 Dart 中调用超类的构造函数和其他语句?

在 Dart 中切换失败

dart中的max/mi int/double 值是否有常数?

Dart,对泛型的限制?

Dart 中不同的 Map 实现有什么区别?

如何在 Dart 中将日期/时间字符串转换为 DateTime 对象?

如何在 Dart 中创建私有变量?