Created
February 7, 2020 07:56
-
-
Save roipeker/b2dfdba0832f25b791daa0cafbc76427 to your computer and use it in GitHub Desktop.
flutter, static snackbar access
This file contains hidden or 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/cupertino.dart'; | |
import 'package:flutter/material.dart'; | |
void main() => runApp(MyApp()); | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
routes: { | |
'/1': (ctx) => MyHome(), | |
'/2': (ctx) => MySecondPage(), | |
}, | |
initialRoute: '/1', | |
debugShowCheckedModeBanner: false, | |
builder: (ctx, child) { | |
return Scaffold( | |
body: Builder(builder: (ctx) { | |
Snacker.context = ctx; | |
return child; | |
}), | |
); | |
}, | |
); | |
} | |
} | |
class Snacker { | |
static BuildContext _context; | |
static set context(val) { | |
_context = val; | |
} | |
static hide([SnackBarClosedReason reason = SnackBarClosedReason.remove]) { | |
Scaffold.of(_context).hideCurrentSnackBar(reason: reason); | |
} | |
static show(SnackBar snackBar) { | |
Scaffold.of(_context).showSnackBar(snackBar); | |
} | |
} | |
class MyHome extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('home'), | |
actions: <Widget>[ | |
IconButton( | |
icon: Icon(Icons.dock), | |
onPressed: () { | |
Snacker.hide(); | |
Snacker.show(SnackBar(content: Text("snackbar page 1"))); | |
}, | |
), | |
], | |
), | |
body: Center( | |
child: Column( | |
mainAxisSize: MainAxisSize.min, | |
children: <Widget>[ | |
Text('hello home!'), | |
RaisedButton( | |
child: Text('go to page 2'), | |
onPressed: () { | |
Navigator.of(context).pushNamed('/2'); | |
}, | |
) | |
], | |
), | |
), | |
); | |
} | |
} | |
class MySecondPage extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('second page'), | |
actions: <Widget>[ | |
IconButton( | |
icon: Icon(Icons.dock), | |
onPressed: () { | |
Snacker.hide(); | |
Snacker.show(SnackBar(content: Text("snackbar page 2"))); | |
}, | |
), | |
], | |
), | |
body: Center( | |
child: Text('hello, second page!'), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment