I've created a Widget that's basically an ElevatedButton, except its width can be made proportional to the screen size (settable with WidthFactor).
import 'package:flutter/material.dart';
class FractionalButton extends StatelessWidget {
final double widthFactor;
final Widget child;
final Function onPressed;
FractionalButton({
required this.widthFactor,
required this.onPressed,
required this.child,
});
@override
Widget build(BuildContext context) {
return FractionallySizedBox(
widthFactor: widthFactor,
child: ElevatedButton(
onPressed: onPressed(),
child: child,
),
);
}
}
Trouble is, it shows up gray instead of using the basic themed color of green.
ElevatedButton(
onPressed: () {},
child: const Text("Country"),
),
FractionalButton(
widthFactor: 1,
onPressed: () {},
child: const Text("Password"),
),
How can I get my Widget to use the current theme colors?
CodePudding user response:
It's not an issue with the ElevatedButton but with the onPressed
function you are passing to the custom ElevatedButton.
Instead of
final Function onPressed;
use
final VoidCallback onPressed;
or
final Function() onPressed;
and use it like below:
onPressed: onPressed,
Your FractionalButton
will look like below.
class FractionalButton extends StatelessWidget {
final double widthFactor;
final Widget child;
final VoidCallback onPressed;
FractionalButton({
required this.widthFactor,
required this.onPressed,
required this.child,
});
@override
Widget build(BuildContext context) {
return FractionallySizedBox(
widthFactor: widthFactor,
child: ElevatedButton(
onPressed: onPressed,
child: child,
),
);
}
}
EDIT
The reason it was happening was you were not passing on onPressed
properly to the custom ElevatedButton and it was set to the disabled mode.
CodePudding user response:
the problem is with te declaration of the function try this :
final void Function() onPressed;
the whole code :
class FractionalButton extends StatelessWidget {
final double widthFactor;
final Widget child;
final void Function() onPressed;
FractionalButton({
required this.widthFactor,
required this.onPressed,
required this.child,
});
@override
Widget build(BuildContext context) {
return FractionallySizedBox(
widthFactor: widthFactor,
child: ElevatedButton(
onPressed: onPressed,
child: child,
),
);
}
}
so when you use this widgets :
ElevatedButton(
onPressed: () {},
child: const Text("Country"),
),
FractionalButton(
widthFactor: 0.5,
onPressed: () { },
child: const Text("Password"),
),
this will be the result:
as you can see it use the same theme as the original ElevatedButton.