I am using flutter web. I am using GetX package to manage my states & navigation. When the app starts everything is working fine and I am able to navigate to other pages without any problems.
The problem is when I press reload on my chrome browser the app breaks I get this error.
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
════════ Exception caught by widgets library ═══════════════════════════════════
The following TypeErrorImpl was thrown building Directionality(textDirection: ltr):
Unexpected null value.
The relevant error-causing widget was
Directionality
../…/root/get_material_app.dart:328
GetMaterialApp code:
GetMaterialApp(
title: 'My Web App',
debugShowCheckedModeBanner: false,
textDirection: TextDirection.ltr,
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: SignIn.routeName,
getPages: [
GetPage(
name: Home.routeName,
page: () => const Home(),
middlewares: [AuthMiddleware()],
),
GetPage(
name: SignIn.routeName,
page: () => SignIn(),
middlewares: [AuthMiddleware()],
),
GetPage(
name: SignUp.routeName,
page: () => SignUp(),
middlewares: [AuthMiddleware()],
),
],
);
I have even added textDirection: TextDirection.ltr. No errors of any type when I first run the app. The app breaks after I click reload.
I think I have a similar setup to you. I'm using GetX for route management.
I am using a static const String routeName = '/_login_page'; field in my Login page.
Here is my GetMaterialApp method:
return GetMaterialApp(
debugShowCheckedModeBanner: false,
textDirection: TextDirection.ltr,
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: LoginPage.routeName,
getPages: [
GetPage(
name: LoginPage.routeName,
page: () => const LoginPage(),
),
],
);
If I change the value of the route field in my Login page while the app is running and reload the browser, it consistently throws that error for me. If I then stop my project and rerun it, my works fine. I suspect the routeName field is being cached and when it's changed during runtime, it no longer matches.
Solution: If you rename your routeName field, stop and then rerun your project.
Related
I have an icon set using a transparent image, on the home screen the background is white but when in the Gesture Navigation view the icon above the app screen is blue. How do I change this background color? (Using flutter)
I am also having this issue. As a work around, I keep the Material App ThemeData's primary color as white. Then used the Theme widget to override my page theme to use my custom theme.
https://api.flutter.dev/flutter/material/ThemeData-class.html
class MyApp extends StatelessWidget {
final _navigatorKey = GlobalKey<NavigatorState>();
NavigatorState? get _navigator => _navigatorKey.currentState;
MyApp({super.key});
// App Routing
Route<dynamic> _generateRoute(RouteSettings settings) {
Widget newPage = Container();
switch (settings.name) {
case AppRoutes.welcome:
newPage = const WelcomePage();
break;
case AppRoutes.login:
newPage = LoginPage();
break;
}
return FadeRoute(
page: Theme(
data: lightTheme,
child: newPage,
),
);
}
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<AppBloc>(
create: (_) => AppBloc()..add(InitializeAppEvent())),
BlocProvider<AuthBloc>(create: (_) => AuthBloc())
],
child: BlocListener<AuthBloc, AuthState>(
listener: (_, state) {
if (state is Authenticated) {
// Go to Main Page
_navigator?.pushReplacementNamed(AppRoutes.home);
} else {
// Go to Login Page
_navigator?.pushReplacementNamed(AppRoutes.login);
}
},
child: MaterialApp(
navigatorKey: _navigatorKey,
title: 'Flutter Demo',
theme: ThemeData(primaryColor: Colors.white),
initialRoute: AppRoutes.welcome,
onGenerateRoute: _generateRoute,
)));
}
}
Thats the primary color you can change it like this
MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.lightGreen,//here.change this one
),
)
It isn't from Android. Flutter's MaterialApp already provides a set of attributes for us, including a Prymary Color, ColorScheme, etc.
The reason is obvious, if every developer had to write every theme aspect in every widget coding would be awful. So Material widgets look for a theme, which Material will provide as default, if we don't overide it.
Know this, the solution is:
Overide some componentes of the whole Theme in the MaterialApp wich is my recomendation. The code bellow is an example of this.
Wrap a specifc widget/s with an Theme widget that overides the define Theme for explict specified atributes.
Pass a custom theme directly in the widgets you are using. Very common to see in Text widgets when people do Text( "some text", style: TextStyle()) (note the TextStyle), but this logic is apllied to a bunch of other widgets too, including buttons. Disavantage of this is that you have to manual change every widget, so no auto darkmode and painfull design changes for reasonable size apps. I do not recomend as a go to solution for every widget.
Example of what I meant by overiding the default Theme of your App:
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Association App for AMDKP Integrated Plataform',
theme: ThemeData(
colorScheme: ColorScheme(
brightness: Brightness.light,
primary: consts.golden1,
onPrimary: consts.black41,
secondary: Colors.green.shade500,
onSecondary: Colors.green.shade300,
background: consts.greyWhite,
onBackground: consts.black41,
surface: Colors.white,
onSurface: Colors.black45,
error: Colors.red.shade900,
onError: Colors.red.shade900,
),
primarySwatch: Colors.blue,
primaryColor: consts.golden1,
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
shadowColor: consts.black41,
primary: Theme.of(context).colorScheme.onSurface.withAlpha(150),
onPrimary: Theme.of(context).colorScheme.surface,
)),
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
primary: Colors.white.withAlpha(230),
backgroundColor: Colors.black87.withAlpha(170),
textStyle: Theme.of(context).textTheme.bodyMedium,
padding: const EdgeInsets.symmetric(horizontal: 10.0),
)),
inputDecorationTheme: const InputDecorationTheme(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: consts.golden1, width: 2)),
),
),
home: const HomePage(),
So definitely take a look at flutter themes, it will empower your flutter developer skills and you will benefit a lot by using it anyway! :)
Cheers
In order to have a globally available method for showing snackbars, i created a Riverpod provider for the ScaffoldMessenger, as it can be found in some examples on the internet:
final scaffoldMessengerKeyProvider = Provider((ref) =>
GlobalKey<ScaffoldMessengerState>());
final scaffoldMessengerProvider = Provider((ref) =>
ref.watch(scaffoldMessengerKeyProvider).currentState!);
return MaterialApp.router(
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
scaffoldMessengerKey: ref.watch(scaffoldMessengerKeyProvider),
...
);
This allows me to show snackbars from anywhere by calling:
widgetRef.read(scaffoldMessengerProvider).showSnackBar(
SnackBar(
content: Text('Hi, i am a SnackBar'),
),
);
Showing the snackbar works fine, but the theme that is being applied to those snackbars seems to be the blue default theme.
How could I apply my own Themes (AppTheme.lightTheme / AppTheme.darkTheme) to this ScaffoldMessenger or just the snackbars? Is there a clean way of doing this, that i'm not seeing?
I think the cleanest way to do it is inside your lightTheme and darkTheme and apply the desired Theme.
Example:
static final darkTheme = ThemeData(
snackBarTheme: const SnackBarThemeData(
actionTextColor: Colors.red,
backgroundColor: Colors.black,
contentTextStyle: TextStyle(color: Colors.white),
elevation: 20
),
I am using easy_localization for translations in my Flutter app. everything is fine but while developing every time I use hot reload the whole app is restarted.
The console shows that easy_localization is reinitialized when hot reload:
and this is my code:
runApp(
ProviderScope(
overrides: [
prefsProvider.overrideWithValue(prefs),
],
child: EasyLocalization(
supportedLocales: const [Locale('en')],
path: 'assets/translations',
fallbackLocale: const Locale('en', 'US'),
child: const RavenApp(),
saveLocale: true,
),
),
);
Note: I tried to remove EasyLocalization and the issue despaired.
I'm using the showAboutDialog function from flutter to show used licences in my project. How ever I'm stuck with changing the text color of the VIEW LICENSES and CLOSE textbuttons. See this image for clarification:
This is my code:
...
onTap: () {
showAboutDialog(
context: context,
applicationName: 'bla',
applicationLegalese: 'November 2023',
);
},
What I tried so far is looking for a color field inside the showAboutDialog how ever I could not find anything. I'm assuming that I could change the color in my MaterialApp ThemeData. Unfortunately I was not able to find the specific theme to override the default styling of those textbuttons.
I tried the following in my MaterialApp ThemeData to change the color of VIEW LICENSES and CLOSE to green but that did not change anything:
textButtonTheme: TextButtonThemeData(style: ButtonStyle(foregroundColor: MaterialStateProperty.all<Color>(Colors.green))
Any ideas about this?
I was not satisfied with the answers here because all were showing only MaterialColor use-cases and I wanted a custom color. But I finally found something explaining it well on the following link.
https://blog.logrocket.com/new-material-buttons-in-flutter/
Basically, what is confusing is that the new design uses the primary color instead of the textStyle property. You can still apply the other answers to change the overall theme using a MaterialColor, and you can override the existing color theme using any color by using primary under TextButton.styleFrom.
Example for anywhere in the app:
TextButton(
onPressed: () {},
style: TextButton.styleFrom(
foregroundColor: Colors.pink,
),
child: Text(
'TextButton (New)',
style: TextStyle(fontSize: 30),
),
)
Example for the theme:
textButtonTheme: TextButtonThemeData(
style: TextButton.styleFrom(
primary: kDarkColor, // This is a custom color variable
textStyle: GoogleFonts.fredokaOne(),
),
),
You can use this:
return MaterialApp(
theme: ThemeData.dark().copyWith(
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith(
(state) => Colors.orange)))),
home: MyWidget(),
);
MaterialStateProperty.resolveWith takes a function, you can specify the color based on states, such as
MaterialState.pressed,
MaterialState.hovered,
MaterialState.focused,
More info on this.
How about this one?
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
colorScheme: ColorScheme.fromSwatch(
primarySwatch: Colors.green,
).copyWith(),
),
debugShowCheckedModeBanner: false,
home: YourScreen(),
);
}
i run this code.
after some research i find out this way to change colour.
for this you need to set application main theme colour change, like this
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.brown,//i am set brown colour,you can set your colour here
),
debugShowCheckedModeBanner: false,
home: YourScreen(),
);
}
after this its work,
showAboutDialog(
context: context,
applicationName: 'bla',
applicationLegalese: 'November 2023',
);
If you want to change the colors only for the dialog and not for the whole app, you have to create a new context. Surround the Button that showing the dialog with a Theme and a Builder
Theme(
data: Theme.of(context).copyWith(
colorScheme: colorScheme.copyWith(primary: Colors.green),
),
child: Builder(
builder: (context) {
return ListTile(
title: Text('show dialog'),
onTap: () => showAboutDialog(
context: context,
...)
);
},
),
)
I was trying to create the Floating Action button but I am missing icon.
My code is:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
centerTitle: true,
title: Text(
"Lessons of Flutter",
style: TextStyle(
color: Colors.white,
),
),
),
body: Center(
child: const Text('Press the button below!')
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here!
},
child: Icon(Icons.mouse),
backgroundColor: Colors.green,
),
),
);
}
}
it is a screen from the virtual device.( You can see icon looks weird.)
To use this class, make sure you set uses-material-design: true in your project's pubspec.yaml file in the flutter section. This ensures that the MaterialIcons font is included in your application. This font is used to display the icons. For example:
Refer this link: https://api.flutter.dev/flutter/material/Icons-class.html
The Icon is not rendering because of the missing font from the material design library. You have to enable the material design library in your pubspec.yml file as given below,
flutter:
uses-material-design: true
Just make uses-material-design to true and the error will be gone. This ensures that the MaterialIcons font is included in your application. This font is used to display the icons Here is the official docs of Icon class