import 'package:flutter/material.dart';

// 抽象类
abstract class BlocBase {
  //获取数据
  Future getData({String labelId, int page});
  // 刷新
  Future onRefresh({String labelId});
  // 加载更多
  Future onLoadMore({String labelId});

  // 可用于Widget释放时能关闭Stream
  void dispose();
}

/// 设计一个BlocProvider StatefulWidget来处理数据，接收两个参数
/// [bloc] bloc对象
/// [child] 子Widget
class BlocProvider<T extends BlocBase> extends StatefulWidget {
  BlocProvider({
    Key key,
    @required this.child,
    @required this.bloc,
    this.userDispose: true,
  }) : super(key: key);

  final T bloc;
  final Widget child;
  final bool userDispose;

  @override
  _BlocProviderState<T> createState() => _BlocProviderState<T>();

  // 返回bloc
  static T of<T extends BlocBase>(BuildContext context) {
    // 通过遍历Element的parent来找到指定类型的Widget
    BlocProvider<T> provider =
        context.findAncestorWidgetOfExactType<BlocProvider<T>>();
    return provider.bloc;
  }

  // static Type _typeOf<T>() => T;
}

class _BlocProviderState<T> extends State<BlocProvider<BlocBase>> {
  @override
  // 资源释放
  void dispose() {
    if (widget.userDispose) widget.bloc.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}
