утилизировать в блоке флаттера

В приведенном ниже коде profileBloc инициализируется в методе didChangeDependencies () EditProfileScreenState.

Должны ли мы вызывать метод dispose в классе EditProfileScreenState для удаления profileBloc?

Если да, то как следует удалить метод profileBloc, поскольку класс ProfileBloc расширяет класс Bloc, у которого нет метода удаления?

class Profile extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) => ProfileBloc(AuthRepo()),
      child: ProfileScreen(),
    );
  }
}

class ProfileScreen extends StatefulWidget {

  @override
  EditProfileScreenState createState() => EditProfileScreenState();
}


class EditProfileScreenState extends State<ProfileScreen> {

  ProfileBloc profileBloc;

  @override
  void didChangeDependencies() {
    profileBloc = BlocProvider.of<ProfileBloc>(context);
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    //profileBloc.dispose() cannot call as ProfileBloc class doesn't have dispose method
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: BlocConsumer<ProfileBloc, ProfileState>(
        listener: (context, state) {
        },
        builder: (BuildContext context,ProfileState state) {
          return RaisedButton(onPressed: ()=>profileBloc.add(SaveProfile("name","email")));
        }
      ));
  }
}

class ProfileBloc extends Bloc<ProfileEvent, ProfileState> {

  AuthRepo authRepo;

  ProfileBloc(this.authRepo) : super(ProfileSaved());

  @override
  Stream<ProfileState> mapEventToState(ProfileEvent event) async* {
    if (event is SaveProfile) {
      //Actions
    }
  }
}

person anandasubedi    schedule 02.08.2020    source источник
comment
блок удаляется только в том случае, если вы используете BlocProvider для его создания, а удаление происходит, когда BlocProvider отключен от дерева виджетов. надеюсь, это поможет   -  person ayoub boumzebra    schedule 02.08.2020


Ответы (1)


Пока искал, нашел решение.

Нам не нужно инициализировать profileBloc в didChangeDependencies ().

Мы можем получить доступ к методу добавления непосредственно из BlocProvider, используя:

BlocProvider.of<ProfileBloc>(context).add(ProfileSaved())

Мы можем удалить следующий раздел из класса EditProfileScreenState.

ProfileBloc profileBloc;

  @override
  void didChangeDependencies() {
    profileBloc = BlocProvider.of<ProfileBloc>(context);
    super.didChangeDependencies();
  }

Более того, в классе ProfileBloc мы можем использовать метод close, если нам нужно отменить какие-либо потоки.

@override
  Future<void> close() {
    //cancel streams
    super.close();
  }
person anandasubedi    schedule 02.08.2020
comment
Вы забыли вернуть будущее ‹void› в своем @override Future ‹void› закрыть () - person neronovs; 29.06.2021