-1

I am trying to make that when I submit the button, the isLoading variable is set to true, and when the block issues the state it returns to false, to show a circular progress indicator. My problem is that I don't know WHERE or HOW to put that variable, nor how to tell the bloc that this variable is true before / outside the BlocBuilder,

this is the code of my button:

TextButton(
                  child: Text("submit"),
                  onPressed: () {
                    
                    context
                        .read<ShowMusicHomeBloc>()
                        .add(OnSearchTracks(q: _searchText.text));

                    
                    _searchText.clear();
                  },
                ),

Could you give me a practical example how I can set this variable isLoading to true using flutter_bloc?

Dubbain
  • 73
  • 1
  • 8

1 Answers1

0

You can make a LoadingState and emit it when you press the button.

abstract class MyState {}

class MyLoadingState extends MyState {}

class MyLoadedState extends MyState {
  final MyData data;
  MyLoadedState(this.data);
}

// other states like ErrorState or InitialState

class MyCubit extends Cubit<MyState>{
  MyCubit(this.someService) : super(MyLoadingState());

  final SomeService someService;

  Future<void> fetchData(){
    emit(MyLoadingState);
    
    final fetchedData = someService.fetchData();
    emit(MyLoadedState(fetchedData));
  }
}

you can apply the same concept to Blocs too.

Adnan Alshami
  • 949
  • 1
  • 7
  • 22