Apply ButtonStyle Properties to All Buttons Globally - flutter

I've implemented several long ListViews containing ElevatedButtons in my flutter project, and would now like to apply various ButtonStyle properties to all of them. I am certain there is a way to avoid applying these properties to each button individually, but haven't been able to find anything in the Flutter docs or on Stack Overflow. Can this task be done globally?
Currently buttons have basic styling:
ElevatedButton(
style: const ButtonStyle(),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => authorA()),
);
},
child: const Text("Author A")),
ElevatedButton(
style: const ButtonStyle(),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AuthorB()),
);
},
child: const Text("Author B")),
ElevatedButton(
style: const ButtonStyle(),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AuthorC()),
);
},
child: const Text("Author C)")),
My ListView contains hundreds of these buttons, and there are several other long ListViews containing buttons that I would like to style as well. what if I wanted to modify the ButtonStyle() property for all of them like below:
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all<Color>(Colors.green),
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => AuthorA()),
);
},
child: const Text("Author A")),

Use theme or darkTheme property of MaterialApp to set global styles.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
primary: Colors.green,
),
),
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}

main.dart
MaterialApp(
theme: ThemeData(
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
primary: Colors.orange,
),
),
),
);

A ButtonStyle that overrides the default appearance of
ElevatedButtons when it's used with ElevatedButtonTheme or with the
overall Theme's ThemeData.elevatedButtonTheme.
The style's properties override ElevatedButton's default style, i.e.
the ButtonStyle returned by ElevatedButton.defaultStyleOf. Only the
style's non-null property values or resolved non-null
MaterialStateProperty values are used.
MaterialApp(
theme: ThemeData(
elevatedButtonTheme: ElevatedButtonThemeData(
style: ElevatedButton.styleFrom(
primary: Colors.orange,
),
),
),
);

Using the same properties add different styles as you want this is possible using .. Operator.
ElevatedButton(
style: const ButtonStyle()..,//Just Add .. here and add new color and properties
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => authorA()),
);
},
child: const Text("Author A")),

use -> MaterialApp -> theme -> elevatedButtonTheme -> style -> with styleForm -> primary : #Color

Related

Dart Flutter: throw FlutterError.fromParts(<DiagnosticsNode>[

I'm making a program for calculations in flutter and when building the package, it throws me to the "debyg.dart" file and points to the line "throw FlutterError.fromParts(<DiagnosticsNode>[". So what should I do with this error. I'm still new to flutter, so I don't know much.
import 'package:flutter/material.dart';
import 'datchik/datchiki.dart';
import 'ThirdPage.dart';
import 'datchik/TCP10P.dart';
import 'datchik/TCP50P.dart';
import 'datchik/TCP100P.dart';
import 'datchik/TCP500P.dart';
import 'datchik/TCP1000P.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => const MyHome(),
'/datchiki': (context) => SecondPage(),
'/ThirdPage': (context) => ThirdPage(),
'/TCP10P': (context) => const TCP10P(),
'/TCP100P': (context) => const TCP100P(),
'/TCP50P': (context) => const TCP50P(),
'/TCP500P': (context) => const TCP500P(),
'/TCP1000P': (context) => const TCP1000P(),
},
),
);
}
class MyHome extends StatelessWidget {
const MyHome({Key? key}) : super (key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 214, 162, 248),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Главная страница",
style: TextStyle(fontSize: 20)),
TextButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(Colors.black),
foregroundColor: MaterialStatePropertyAll(Colors.white)
),
onPressed: () {
Navigator.pushNamed(context, '/datchiki');
},
icon: const Icon(Icons.settings),
label: const Text('Датчики температур'),
),
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(Colors.black),
foregroundColor: MaterialStatePropertyAll(Colors.white)
),
onPressed: () {
Navigator.pushNamed(context, '/ThirdPage');
},
icon: const Icon(Icons.settings),
label: const Text('ТСП - 50П')
),
],
)
),
)
);
}
}
TCP-10P.dart The file in which the error appears
import 'package:flutter/material.dart';
import 'datchik/datchiki.dart';
import 'ThirdPage.dart';
import 'datchik/TCP10P.dart';
import 'datchik/TCP50P.dart';
import 'datchik/TCP100P.dart';
import 'datchik/TCP500P.dart';
import 'datchik/TCP1000P.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: '/',
routes: {
'/': (context) => const MyHome(),
'/datchiki': (context) => SecondPage(),
'/ThirdPage': (context) => ThirdPage(),
'/TCP10P': (context) => const TCP10P(),
'/TCP100P': (context) => const TCP100P(),
'/TCP50P': (context) => const TCP50P(),
'/TCP500P': (context) => const TCP500P(),
'/TCP1000P': (context) => const TCP1000P(),
},
),
);
}
class MyHome extends StatelessWidget {
const MyHome({Key? key}) : super (key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color.fromARGB(255, 214, 162, 248),
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Главная страница",
style: TextStyle(fontSize: 20)),
TextButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(Colors.black),
foregroundColor: MaterialStatePropertyAll(Colors.white)
),
onPressed: () {
Navigator.pushNamed(context, '/datchiki');
},
icon: const Icon(Icons.settings),
label: const Text('Датчики температур'),
),
ElevatedButton.icon(
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(Colors.black),
foregroundColor: MaterialStatePropertyAll(Colors.white)
),
onPressed: () {
Navigator.pushNamed(context, '/ThirdPage');
},
icon: const Icon(Icons.settings),
label: const Text('ТСП - 50П')
),
],
)
),
)
);
}
}
Debug.dart The file where it throws me
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('No Material widget found.'),
ErrorDescription(
'${context.widget.runtimeType} widgets require a Material '
'widget ancestor.\n'
'In Material Design, most widgets are conceptually "printed" on '
"a sheet of material. In Flutter's material library, that "
'material is represented by the Material widget. It is the '
'Material widget that renders ink splashes, for instance. '
'Because of this, many material library widgets require that '
'there be a Material widget in the tree above them.',
),
ErrorHint(
'To introduce a Material widget, you can either directly '
'include one, or use a widget that contains Material itself, '
'such as a Card, Dialog, Drawer, or Scaffold.',
),
...context.describeMissingAncestor(expectedAncestorType: Material),
]);
I tried changing the SizedBox parameters, but nothing worked. Maybe I just did it wrong

I've been trying to create the button to navigate to the second page but somehow the RaisedButton function did't work out

I have been following the yt video on creating the navigation map button but I don't understand what did I do wrong on RaisedButton line (I put in stars infront and at the back)
import 'package:flutter/material.dart';
import 'package:ionicons/ionicons.dart';
import 'package:avenique/pages/PlanningPaymentScreen.dart';
class RootApp extends StatelessWidget {
RootApp({super.key});
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {
print("menu pressed");
},
icon: Icon(Icons.menu)),
title: Text("PlanningPage"),
actions: <Widget>[
IconButton(
onPressed: () {
print("search pressed");
},
icon: Icon(Icons.search)),
],
),
body: Center(
** child:RaisedButton( **
child: Text(
'Next Screen',
style: TextStyle(
color: Color.fromARGB(255, 255, 255, 255),
),
),
Color: Color.fromARGB(255, 0, 0, 0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PlanningPaymentScreen()),
);
}),
),
);
}
}
I expected the code to run smoothly. Thankyou for the help!
Since RaisedButton is deprecated. try using " ElevatedButton " and you will find a function inside then you can push.
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
}

Theme.of(context) not passed to simpleDialog

I'm using a showDialog function in my app. The themeData is not passed from my parent widget to my showDialog. Can anyone tell me why it's not working? I have to specify the theme is working everywhere else but not in my showDialog. I'm using provider to change the theme accordingly to dark and light. Anyways, in the code just below the showDialog it works.
Widget build(BuildContext context) {
Cart cartProvider = Provider.of<Cart>(context);
Future<Future> showDialogFunction(BuildContext context) {
// showing basket cart
return showDialog(
context: context,
builder: (BuildContext context) {
Widget cartDialog = BackdropFilter(
filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
child: SimpleDialog(
backgroundColor: Colors.transparent,
children: [
Consumer<Cart>(builder: (context, cart, child) {
return Container(
height: 1.sh,
width: 0.8.sw,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
icon: const Icon(Icons.close),
color: mainSecondaryColor,
onPressed: () {
Navigator.pop(context);
},
),
Text('Cosul meu',
style: TextStyle(color: Theme.of(context).colorScheme.primary)),
My main.dart file:
class FinerApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => ThemeNotifier(),
child: ScreenUtilInit(
designSize: Size(360, 690),
allowFontScaling: true,
builder: () => Consumer<ThemeNotifier>(
builder: (context, ThemeNotifier notifier, child) {
return Provider<AuthBase>(
create: (context) => Auth(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter_ScreenUtil',
home: MaterialApp(
debugShowCheckedModeBanner: false,
theme: notifier.darkTheme
? CustomTheme.darkTheme
: CustomTheme.lightTheme,
home: LandingPage(),
routes: routes,
),
),
);
})));
}
}
The problem is you're not using the context which is given by the build method. Change the variable name of your build method like this:
Widget build(BuildContext buildContext) {...}
And then use
Theme.of(buildContext).textTheme.caption)
Using a Theme like this
declare theme in MaterialApp
MaterialApp(
title: appName,
theme: ThemeData(
// Define the default brightness and colors.
brightness: Brightness.dark,
primaryColor: Colors.lightBlue[800],
accentColor: Colors.cyan[600],
// Define the default font family.
fontFamily: 'Georgia',
// Define the default TextTheme. Use this to specify the default
// text styling for headlines, titles, bodies of text, and more.
textTheme: TextTheme(
headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
),
home: MyHomePage(
title: appName,
),
);
use the theme likethis
Container(
color: Theme.of(context).accentColor,
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.headline6,
),
),
find more here:
https://flutter.dev/docs/cookbook/design/themes#using-a-theme

Flutter - How can I change the background color of LicensePage?

I'd like to set the background colour of every screen except LicensePage to some colour, so I've specified the scaffoldBackbroundColor via the theme argument of MaterialApp as follows.
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(scaffoldBackgroundColor: Colors.blue.shade200),
home: HomeScreen(),
);
}
}
This changes the background colour of the licences page too, so in order to change it back to white, I tried overriding scaffoldBackbroundColor, but it did not work.
class HomeScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Theme(
data: Theme.of(context).copyWith(scaffoldBackgroundColor: Colors.white),
child: Center(
child: RaisedButton(
child: const Text('Show licenses'),
onPressed: () => showLicensePage(context: context),
),
),
),
);
}
}
How can I do it?
In my case I found ThemeData(cardColor) was dictating the LicensePage background color. So,
showLicense(BuildContext context) {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => Theme(
data: ThemeData(
cardColor: Colors.yellow,
),
child: LicensePage(
applicationVersion: '0.1',
applicationIcon: Icon(Icons.person),
applicationLegalese: 'Legal stuff',
),
),
),
);
}
I came up with this and it worked successfully.
Scaffold(
body: Center(
child: RaisedButton(
child: const Text('Show licenses'),
onPressed: () => Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => Theme(
data: Theme.of(context).copyWith(
scaffoldBackgroundColor: Colors.white,
),
child: LicensePage(...),
),
),
),
),
),
)
This way you cannot set the theme, set color using Container
Scaffold(
body: Container(
color: Colors.white,
child: Center(
child: RaisedButton(
child: const Text('Show licenses'),
onPressed: () => showLicensePage(context: context),
),
),
),
),

error when I use raisedButton in a widget

I am writing my first flutter app and i created two classes.
Those two classes represent two pages that i wish to navigate between and I am facing an issue with the "raisedButton".
The first class has 2 widgets and the button only works in one of them! whenever I try to cut+ paste the button to the desired widget => I get the following error:
The method 'findAncestorStateOfType' was called on null.
Receiver: null
Tried calling: findAncestorStateOfType()
I don't know what they mean by that.
Any help is appreciated.
class FirstRoute extends StatelessWidget {
Widget _contactList(String name, String image,[BuildContext context]) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.red,
backgroundImage: AssetImage(image),
radius: 35.0,
child: Text(nameInitial,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0)),
),
title: Text(name),
trailing: RaisedButton(
textColor: Colors.white,
color: Colors.blue,
child: Text('Details'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Details()),
);
},
),
),
);
}
you can use a named route by calling the Navigator.pushNamed(context,'/home'); Named routes allow for parameter passing '/customer/:${customer.id}'. the routing paths are defined onGenerateRoute attribute assigned to routing information
class _AppWidgetState extends State<AppWidget>{
bool _bright=false;
_brightnessCallback().
{setState(()=>_bright=!_bright);debugPrint("brightnessCallback fired");}
#override
Widget build(BuildContext context){
return MaterialApp(
title: "Flutter demo",
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHome2Widget(),
onGenerateRoute: handleRoute
);
}}
Route<dynamic> handleRoute(RouteSettings routeSettings)
{
List<String> nameParam= routeSettings.name.split(":");
String name=nameParam[0];
//int id=int.tryParse(nameParam[1]);
Widget childWidget;
if(name=="/Home")
{
childWidget=MyHome2Widget();
}else if(name=="/Summary")
{
childWidget=SummaryWidget();
}
return MaterialPageRoute(
builder:(context)=>childWidget
);
}