утилизировать в блоке флаттера - PullRequest
0 голосов
/ 02 августа 2020

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

Следует ли вызывать метод dispose в классе EditProfileScreenState для удаления profileBlo c?

Если да, то как следует удалить метод profileBlo c, поскольку класс ProfileBlo c расширяет класс Blo c, у которого нет метода удаления?

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
    }
  }
}

1 Ответ

0 голосов
/ 02 августа 2020

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

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

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

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

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

ProfileBloc profileBloc;

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

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

@override
  Future<void> close() {
    //cancel streams
    super.close();
  }
...