Last active
September 13, 2021 21:33
-
-
Save felangel/1e5b2c25b263ad1aa7bbed75d8c76c44 to your computer and use it in GitHub Desktop.
[flutter_bloc_recipes] Show 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/material.dart'; | |
import 'package:bloc/bloc.dart'; | |
import 'package:flutter_bloc/flutter_bloc.dart'; | |
import 'package:meta/meta.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return BlocProvider( | |
create: (context) => DataBloc(), | |
child: MaterialApp( | |
home: Home(), | |
), | |
); | |
} | |
} | |
class Home extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(title: Text('Home')), | |
body: BlocListener<DataBloc, DataState>( | |
listener: (context, state) { | |
if (state is Success) { | |
Scaffold.of(context).showSnackBar( | |
SnackBar( | |
backgroundColor: Colors.green, | |
content: Text('Success'), | |
), | |
); | |
} | |
}, | |
child: BlocBuilder<DataBloc, DataState>( | |
builder: (context, state) { | |
if (state is Initial) { | |
return Center(child: Text('Press the Button')); | |
} | |
if (state is Success) { | |
return Center(child: Text('Success')); | |
} | |
return Center(child: CircularProgressIndicator()); | |
}, | |
), | |
), | |
floatingActionButton: Column( | |
crossAxisAlignment: CrossAxisAlignment.end, | |
mainAxisAlignment: MainAxisAlignment.end, | |
children: <Widget>[ | |
FloatingActionButton( | |
child: Icon(Icons.play_arrow), | |
onPressed: () { | |
context.read<DataBloc>().add(FetchData()); | |
}, | |
), | |
], | |
), | |
); | |
} | |
} | |
@immutable | |
abstract class DataEvent {} | |
class FetchData extends DataEvent {} | |
@immutable | |
abstract class DataState {} | |
class Initial extends DataState {} | |
class Loading extends DataState {} | |
class Success extends DataState {} | |
class DataBloc extends Bloc<DataEvent, DataState> { | |
DataBloc() : super(Initial()) { | |
on<FetchData>((event, emit) async { | |
emit(Loading()); | |
await Future.delayed(Duration(seconds: 2)); | |
emit(Success()); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for help.. i will try to implement this... l will have to play with it. still learning class / oop. maybe a future tutorial on cubit managing multiple states would be great ...