In this post let's see how we can create a MultiStateView widget that will show the data to the user based on the view state and helps us to avoid the conditional statements we write on every data centric widget to check the state in order to show the appropriate view. Normally, the views we are creating can have four different states ,

1) Loading State
2) Success/Content State 
3) Error State
4) Empty State

As we know the different view states, let's create an enum class

enum ViewState {
  Content,
  Loading,
  Error,
  Empty
}
z

Basically, the MultiStateView we are creating will have a ViewState variable and four widgets that will be showed based on the view state.That's it! It's simple but will save us from writing more boilerplate codes and also make the code look clean.

class MultiStateView extends StatelessWidget {

  final ViewState _state;
  final Widget _contentView,_loaderView,_emptyView,_errorView;
  
  MultiStateView({
      @required this._state,
      @required this._contentView,
      this._errorView,
      this._emptyView,
      this._loaderView
  });

  Widget _getView(){
    switch (_state) {
      case ViewState.Empty:
        return _emptyView??Text("No Empty View Provided");
      case ViewState.Loading:
        return _loaderView??Text("No Loading View Provided");
      case ViewState.Error:
        return _errorView??Text("No Error View Provided");
      default:
        return _contentView;
    }
  }

  @override
  Widget build(BuildContext context) {
    return _getView();
  }
}