Created
January 4, 2019 00:02
-
-
Save ScholliYT/d26dc1b947ff48eb0c96bc7c6d4e086e to your computer and use it in GitHub Desktop.
Flutter redux error snackbar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/foundation.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:flutter/widgets.dart'; | |
import 'package:flutter_redux/flutter_redux.dart'; | |
import 'package:pjapp_flutter/actions/errors_action.dart'; | |
import 'package:pjapp_flutter/models/app_state.dart'; | |
import 'package:redux/redux.dart'; | |
class ErrorSnackbar extends StatelessWidget { | |
ErrorSnackbar({Key key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return StoreConnector<AppState, _ViewModel>( | |
onWillChange: (_viewModel) { | |
final snackBar = SnackBar( | |
content: Text(_viewModel.errormsg), | |
backgroundColor: Colors.red, | |
action: SnackBarAction( | |
label: 'Dismiss', | |
onPressed: () { | |
Scaffold.of(context).hideCurrentSnackBar(reason: SnackBarClosedReason.dismiss); | |
}, | |
), | |
); | |
Scaffold.of(context).showSnackBar(snackBar); | |
_viewModel.errorHandledCallback(); | |
}, | |
converter: _ViewModel.fromStore, | |
distinct: true, | |
builder: (context, vm) { | |
// TODO: Don't use a UI Widget here. This "Widget" should not be visible because its only there to display the snackbar if needed | |
return const Text(""); | |
}, | |
); | |
} | |
} | |
class _ViewModel { | |
final String errormsg; | |
final Function errorHandledCallback; | |
_ViewModel({ | |
@required this.errormsg, | |
@required this.errorHandledCallback, | |
}); | |
static _ViewModel fromStore(Store<AppState> store) { | |
return _ViewModel( | |
errormsg: store.state.error, | |
errorHandledCallback: () { | |
store.dispatch(new ClearError()); | |
} | |
); | |
} | |
@override | |
bool operator ==(Object other) => | |
identical(this, other) || | |
other is _ViewModel && | |
runtimeType == other.runtimeType && | |
errormsg == other.errormsg; | |
@override | |
int get hashCode => errormsg.hashCode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment