Last active
October 15, 2021 19:50
-
-
Save mdrideout/dd5ea3380bac7c97936160d334736cb5 to your computer and use it in GitHub Desktop.
Create context in a situation where you may not have access to it. For example, if need to pass a translated message (requiring context) using `AppLocalizations.of(context)!.message` to a SnackBar from a function where we have no context, we can make the SnackBar argument a function that takes BuildContext as a param, and later get that param fr…
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/material.dart'; | |
const Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
/// Global Scaffold Messenger Key (SnackBars) | |
final GlobalKey<ScaffoldMessengerState> rootScaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>(); | |
void main() { | |
runApp(MyApp()); | |
} | |
class ShowSnackBar { | |
static builtSnackBar({required String Function(BuildContext context) stringBuilder}) { | |
Widget _content = Builder( | |
builder: (BuildContext context) { | |
String _message = stringBuilder(context); | |
return Text(_message); | |
}, | |
); | |
final snackBar = SnackBar(content: _content); | |
final scaffoldMessengerState = rootScaffoldMessengerKey.currentState; | |
if (scaffoldMessengerState != null) { | |
scaffoldMessengerState.showSnackBar(snackBar); | |
} else { | |
print("SnackBar root state is null, cannot display SnackBar."); | |
} | |
} | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith( | |
scaffoldBackgroundColor: darkBlue, | |
), | |
scaffoldMessengerKey: rootScaffoldMessengerKey, | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
body: Center( | |
child: MyWidget(), | |
), | |
), | |
); | |
} | |
} | |
class MyWidget extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return ElevatedButton(onPressed: () { showSnackBar(); }, child: const Text("Show SnackBar"), | |
); | |
} | |
void showSnackBar() { | |
ShowSnackBar.builtSnackBar(stringBuilder: (BuildContext context) { return AppLocalizations.of(context)!.errorsProcessing; }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment