Keep global ThemeData across screens - flutter

Is it possible to set ThemeData globally so you don't have to on the next screens?
Currently after I use the Navigator.pushI have to make sure the new screen Widget have instructions like Theme.of(context).backgroundColor
Is there a way for the app screens/widgets to automatically pick whatever is set in the main.dart theme?
Eg, Here is my main.dart
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(backgroundColor: Colors.red, primaryColor: Colors.green),
home: LoadingScreen(),
);
}
}
and this is the loadingscreen:
class _LoadingScreenState extends State<LoadingScreen> {
#override
void initState() {
super.initState();
getFiles();
}
void getFiles() async {
await Future.delayed(Duration(seconds: 3));
Navigator.push(context, MaterialPageRoute(builder: (context) {
return StartScreen(file: null);
}));
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Theme.of(context).backgroundColor,
child: Center(
child: Image.asset(
height: 100.0,
)),
),
);
}
}
Without a Theme.of(context).backgroundColor in the Container, the app will load a white page behind the image, instead of red as defined in the ThemeData.
Is that a way to avoid the extensive usage of Theme.of(context).backgroundColor everywhere?

When you set the Scaffolds backgroundcolor in the ThemeData every Scaffold should use that color as a backgroundcolor. On your LoadingScreen the extra Container is unecessery since it would override the Scaffolds backgroundcolor.
Refer to this answer on how to set the backgroundcolor: https://stackoverflow.com/a/55581726/13406356

Related

Is MaterialApp/Scaffold absorb my Listener?

I try to code a very simple Whiteboard. When I use
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
child: Listener(
the app isn't recognizing any mouseclick (onPointerDown()). When I use directly
Widget build(BuildContext context) {
return Container(
child: Listener(
everything is ok and I can see some action in the onPointerDown(). So, I think I miss something. I want to use the MaterialApp, to get access to some of the features.
What I tried so far:
At first, I tried to minimize my function, to focus on only that problem.
So, this is my full minimized code:
import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
#override
AppState createState() => AppState();
}
class AppState extends State<App> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Container(
color: Colors.white,
child: Listener(
onPointerDown: (details) {
print('Action');
},
child: CustomPaint(
painter: DrawingPainter(),
),
))));
}
}
class DrawingPainter extends CustomPainter {
DrawingPainter();
#override
void paint(Canvas canvas, Size size) {}
#override
bool shouldRepaint(DrawingPainter oldDelegate) => true;
}
What I recognized, the size of the DrawingPainter is (0.0, 0.0). Maybe the Problem is that the Painter isn't span about the full size? If this is so, how can I change that? I tried to set the size, but ended with size == 0.0, 0.0 again.
Yes, you just have to use a SizedBox.expand or anything that will force your content to expand its size to match parent.
see https://zu4c06ylu4d0.zapp.page/#/

Globally remove all drop shadows in Flutter app?

Is there a way to globally remove all drop shadows in Flutter app?
I would like to do that in single place instead of setting elevation: 0 for all MaterialButtons, ElevatedButtons, etc.
I would like set theme, or do it another way, but globally in single palce.
I was looking for attributes in ThemeData, but can't find desired attributes, e.g. for MaterialButtons.
You were on the right track, ThemeData has an attribute for ElevatedButtons, i have made a small example on what you need to remove shadows based on MaterialStateProperty:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
//this is the function that deletes shadows
double getElevation(Set<MaterialState> states) {
return 0;
}
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light().copyWith(
//this is the property that affects elevated buttons
elevatedButtonTheme: ElevatedButtonThemeData(
style: ButtonStyle(
elevation: MaterialStateProperty.resolveWith(getElevation)))),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
//this button doesn't have a shadow
return ElevatedButton(
child: const Text("HEY!"),
onPressed: () {},
);
}
}
The solution is pretty straightforward,
ThemeData(
shadowColor: Colors.transparent,
);
gets the job done

how to use the theme of TabBar?

i created a theme for TabBar, which is:
class AppWidget extends StatelessWidget {
const AppWidget();
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
tabBarTheme: TabBarTheme(
unselectedLabelColor: Colors.black, // and so on
),),
home: const HomePage(),
);},);}
}
when i use TabBar the is no implementation of the theme, which i have been created. How can i use the TabBar theme above inside TabBar implementation?
the code of TabBar is:
class HomeCustomAppBar extends StatelessWidget with PreferredSizeWidget {
#override
Widget build(BuildContext context) {
return Container(
child: AppBar(
// how to get the TabBar Theme here?
bottom:TabBar([]),
),
);
}
#override
Size get preferredSize => Size.fromHeight(140);
}
Ideally you should not need to use directly the TabBarTheme it should be applied automatically to all TabBar's after setting in in the ThemeData. Nevertheless if you still wish to access it you can by just using :
TabBarTheme.of(context)

'setState' not working in navigated page if custom color is used

For some reason, whenever I navigate to another route using the way described in flutter's documentation i.e https://flutter.dev/docs/cookbook/navigation/navigation-basics, and if I have used custom color in the following way:
color: Color(0xff0e0f26),
in that route, the setState method doesn't work in it. However, if I use color in the following way: color: Colors.blue, the setState method works. I have no idea what is causing this. I want to use a color value that is not present amongst the colors that flutter provides. How do I fix this? The full code along with explanation (using comments) is here:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'test',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: homepage(),
);
}
}
class homepage extends StatefulWidget{
#override
_homepageState createState() => _homepageState();
}
class _homepageState extends State<homepage>{
#override
Widget build(BuildContext context){
return Scaffold(
body: Container(
alignment: Alignment.center,
color: Color(0xff0e0f26),
child: RaisedButton(
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
),
)
);
}
}
class SecondRoute extends StatefulWidget{
#override
_SecondRouteState createState() => _SecondRouteState();
}
class _SecondRouteState extends State<SecondRoute>{
bool test = false;
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
title: Text("Second"),
),
body: Container(
alignment: Alignment.center,
color: Color(0xff0e0f26), //Here, if I use 'color: Colors.blue', setState works.
child:Column(
children: [
RaisedButton(
onPressed: (){ //When the button is pressed, setState is triggered.
setState((){ //This should theoretically rebuild the widget with 'test' becoming true
//, thus showing the text widget below in the screen, but it doesn't.
test = true;
});
},
),
test ? Text("HELLO"):SizedBox(), //I want 'test' to become true, thus making the text
//widget come on screen.
],
),
),
);
}
}
Thank you.
Your text ist just too dark.
If you use
test ? Text("HELLO", style: TextStyle(color: Colors.white30),):SizedBox(),
it should work. This just makes your text lighter. You should use ElevatedButton instead of RaisedButton, since RaisedButton is deprecated and could cause problems as well.

showDialog from root widget

I want to show a dialog from root widget (the one that created MaterialApp) I have a NavigatorState instance, but showDialog requires context that would return Navigator.of(context).
It looks like I need to provide context from a route, but I can't do this, because the root widget does not have it.
EDIT: I have found a workaround: I can push fake route that is only there to showDialog and then pop that route when dialog finishes. Not pretty but works.
I fixed the problem by using navigatorKey.currentState.overlay.context. Here is example:
class GlobalDialogApp extends StatefulWidget {
#override
_GlobalDialogAppState createState() => _GlobalDialogAppState();
}
class _GlobalDialogAppState extends State<GlobalDialogApp> {
final navigatorKey = GlobalKey<NavigatorState>();
void show() {
final context = navigatorKey.currentState.overlay.context;
final dialog = AlertDialog(
content: Text('Test'),
);
showDialog(context: context, builder: (x) => dialog);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
home: Scaffold(
body: Center(
child: RaisedButton(
child: Text('Show alert'),
onPressed: show,
),
),
),
);
}
}
tl;dr: If you want to call showDialog from your root widget, extrude your code into another widget (e.g. a StatelessWidget), and call showDialog there.
Anyway, in the following I'm going to assume you are running into this issue:
flutter: No MaterialLocalizations found.
flutter: MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
flutter: Localizations are used to generate many different messages, labels,and abbreviations which are used by the material library.
As said before, showDialog can only be called in a BuildContext whose ancestor has a MaterialApp. Therefore you can't directly call showDialogif you have a structure like this:
- MaterialApp
- Scaffold
- Button // call show Dialog here
In a code example this would result in code like this, throwing the error given above:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(),
home: Scaffold(
body: Center(
child: RaisedButton(
child: Text('Show dialog!'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
child: Text('Dialog.'),
);
});
}),
),
),
);
}
}
To solve this error from occuring you can create a new Widget, which has its own BuildContext. The modified structure would look like this:
- MaterialApp
- Home
- Home // your own (Stateless)Widget
- Button // call show Dialog here
Modifying the code example to the structure given above, results in the code snippet below. showDialogcan be called without throwing the error.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(),
home: Home()
);
}
}
class Home extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
child: Text('Show dialog!'),
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
child: Text('Dialog.'),
);
});
}),
),
);
}
}
They changed the way the navigator overlay works.
This is the working solution for us as the accepted one isn't anymore.
// If you want to use the context for anything.
final context = navigatorKey.currentState.overlay.context;
// How to insert the dialog into the display queue.
navigatorKey.currentState.overlay.insert(anyDialog);
If you already have a context object, you can get root material app's context by
final rootContext = context.findRootAncestorStateOfType<NavigatorState>().context
and passing this to showDialog or showModalBottomSheet context argument.
Since showDialog is used for showing a material dialog It can be used for showing dialogs inside a MaterialApp widget only. It can not be used to show dialog outside it.
If it helps anyone else, inject the navigator key into a dialog widget like so.
class MyApp extends StatelessWidget {
MyApp({Key key});
final navigatorKey = GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: navigatorKey,
onGenerateRoute: Router.generateRoute,
// ...
builder: (context, routeChild) {
return Material(
child: InviteRequestModal(
navigatorKey: navigatorKey,
child: routeChild,
),
);
},
);
}
Then in the Widget that requires the modal, you can use it as mentioned above.
class InviteRequestModal extends StatelessWidget {
final Widget child;
final GlobalKey<NavigatorState> navigatorKey;
InviteRequestModal({
Key key,
this.child,
this.navigatorKey,
}) : super(key: key);
void _showInviteRequest(InviteRequest invite) {
final context = navigatorKey.currentState.overlay.context;
showDialog(
context: context,
builder: (_) {
// Your dialog content
return Container();
}
);
}
#override
Widget build(BuildContext context) {
return BlocListener<InviteContactsBloc, InviteContactsState>(
listenWhen: (previous, current) => current is InviteRequestLoaded,
listener: (_, state) {
if (state is InviteRequestLoaded) {
_showInviteRequest(state.invite);
}
},
child: child,
);
}
}
The answer just that simple, when you are providing MaterialApp to the tree it was providing but at the immediate bottom you are the context which obtained before providing MaterialApp to the tree. To resolve the issue you need to create a new context which will have the MaterialApp properties. For that wrap a Builder above the home and vola it is working...!
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Builder(builder: (context) {
return HomePage(
child: Center(
child: TextButton(
onPressed: () async {
await showDialog(
context: context,
builder: (context) => Dialog(
child: Container(
color: Colors.green,
height: 50,
width: 100,
child: Text("Hi, I am a dialog"),
),
),
);
},
child: Text("Tap me"),
),
),
);
}),
);
}
For those wanting to see how to do this in a multiple widget/route/file scenario, I used it with InheritedWidget and an extension on BuildContext.
main.dart
import 'package:flutter/material.dart';
import 'package:myapp/home_screen.dart';
import 'package:myapp/app_navkey.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
final navigatorKey = GlobalKey<NavigatorState>();
#override
Widget build(BuildContext context) {
return AppNavKey(
navigatorKey: navigatorKey,
child: MaterialApp(
navigatorKey: navigatorKey,
theme: ThemeData(),
home: Scaffold(
body: HomeScreen(),
),
),
);
}
}
home_screen.dart
import 'package:myapp/extensions.dart';
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
final overlayContext = context.navigationKey().currentState.overlay.context;
return Center(
child: TextButton(
child: Text('Show dialog!'),
onPressed: () {
showDialog(
context: overlayContext, // use app level navigation context overlay
builder: (BuildContext context) {
return Dialog(
child: Text('Dialog.'),
);
});
},
),
);
}
}
app_navkey.dart
import 'package:flutter/widgets.dart';
class AppNavKey extends InheritedWidget {
final Widget child;
final GlobalKey<NavigatorState> navigatorKey;
AppNavKey({
Key key,
#required this.child,
#required this.navigatorKey,
}) : super(key: key, child: child);
static GlobalKey<NavigatorState> of(BuildContext context) {
final ctx = context.dependOnInheritedWidgetOfExactType<AppNavKey>();
if (ctx == null) throw Exception('Could not find ancestor of type AppNavProvider');
return ctx.navigatorKey;
}
#override
bool updateShouldNotify(covariant InheritedWidget oldWidget) => false;
}
extensions.dart
import 'package:flutter/widgets.dart';
import 'package:myapp/app_navkey.dart';
extension SwitchTabContext on BuildContext {
/// Get app level NavigatorState key.
/// ```dart
/// context.navigationKey();
/// ```
GlobalKey<NavigatorState> navigationKey() => AppNavKey.of(this);
}