基础库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

44 lines
1.3 KiB

  1. // Generic Interface for all BLoCs
  2. import 'package:flutter/material.dart';
  3. // 用法参考 https://www.dazhuanlan.com/2019/10/05/5d9835e2149ec/?__cf_chl_jschl_tk__=c887a5bbcade5b1c4e512e339d6456adc0a9e1e8-1589771890-0-AaeNBGzxeReSfKWxA7TZlNbvVfXjv759gU0mNNvmcB14JVlRVGLhl1cVJAVapb4Nc6W_mcSvPtAJQQ8okAWy4d9SdnrUcUJmZQJq2XP59oNFEEAg5oP9GhCHMvR2bqpWQzZXIKgIn3m_GvRMZ1B5lpGP-HPtkjjpb4vO4NHzRgnwwRJtm3-HEeknIa53PShS5wY4EEPXI4i8UdtJRc8oXlzYdNFzVJ_QteCKS6v2jsmP4LzGFo3zFspPF63dj5px-6nMLQlz2sKFSimTI7DQD4baHMDDSZr_4G_vohZjy7Ye1Qy_JHWTT_2TkW60f99AwA
  4. abstract class BlocBase {
  5. void dispose();
  6. }
  7. // Generic BLoC provider
  8. class BlocProvider<T extends BlocBase> extends StatefulWidget {
  9. BlocProvider({
  10. Key key,
  11. @required this.child,
  12. @required this.bloc,
  13. }) : super(key: key);
  14. final T bloc;
  15. final Widget child;
  16. @override
  17. _BlocProviderState<T> createState() => _BlocProviderState<T>();
  18. static T of<T extends BlocBase>(BuildContext context) {
  19. final type = _typeOf<BlocProvider<T>>();
  20. BlocProvider<T> provider = context.ancestorWidgetOfExactType(type);
  21. return provider.bloc;
  22. }
  23. static Type _typeOf<T>() => T;
  24. }
  25. class _BlocProviderState<T> extends State<BlocProvider<BlocBase>> {
  26. @override
  27. void dispose() {
  28. widget.bloc.dispose();
  29. super.dispose();
  30. }
  31. @override
  32. Widget build(BuildContext context) {
  33. return widget.child;
  34. }
  35. }