how can i change color of these iconbuttons by pressing it, please help me and show me whole code for it,
Thanks
In setState you have to add boolean variable, for example changeColor = false;
Then in button :
color: changeColor ? Colors.grey : Colors.blue,
onPressed: () => setState(() => changeColor = !changeColor),
Flutter - How do I toggle the color of a RaisedButton upon click?
This is new method to change color,
there is youtube video for this Here and a article for this Article
ElevatedButton(
child: Text('Elevated Button'),
onPressed: () {
print('Pressed');
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) return Colors.green;
return Colors.greenAccent;
},
),
),
)
You can change the background color of the ElevatedButton using MaterialStateProperty class. You can change the color of the button based on the states too. See the code snippet given below.
IconButton in flutter has a color variable you can set as here:
IconButton(
color: Colors.green,
icon: Icon(Icons.camera),
onPressed: () {},
)
This is the code that I would use:
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: MyWidget(),
);
}
}
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: SingleChildScrollView(
child: Column(children: [
const Text(
'Choose Category',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w600,
),
),
Row(children: [
CategoryButton(
svg: 'assets/candy.svg',
label: 'Tech',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'Finance',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'Design',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'File',
selected: false,
),
CategoryButton(
svg: 'assets/candy.svg',
label: 'Music',
selected: false,
),
])
]),
),
),
);
}
}
class CategoryButton extends StatefulWidget {
CategoryButton({
Key? key,
required this.svg,
required this.label,
required this.selected,
}) : super(key: key);
String svg;
String label;
bool selected;
#override
State<CategoryButton> createState() => _CategoryButtonState();
}
class _CategoryButtonState extends State<CategoryButton> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
widget.selected = !widget.selected;
});
print(widget.selected);
},
child: Container(
height: 40,
width: 40,
decoration: BoxDecoration(
color: widget.selected ? Colors.blue : Colors.black,
borderRadius: BorderRadius.circular(90),
),
child: Column(
children: [
SvgPicture.asset(widget.svg,
color: widget.selected ? Colors.white : Colors.blue),
Text(
widget.label,
style: TextStyle(
color: Colors.white,
fontSize: 9,
fontWeight: FontWeight.w500,
),
),
],
)),
);
}
}
here you need to make sure to add flutter_svg to your pubspec.yaml file and have a folder for your assets and add that to your pubspec.yaml file as well
if you have any further questions just ask :)
Related
I wanna add effect on button ,like while we press the button , background color of button should get change to transparent and button borderline color should be enable, then we release the button , background color get back into yellow color and borderline color should get disable.
Here is some code which I tried button but It doesn't work properly.
class CustomButton extends StatefulWidget {
final void Function()? onPressed;
final String lable;
final int backgroundColor;
final Color textColor;
final FontWeight fontWeight;
final EdgeInsetsGeometry margin;
const CustomButton(
{Key? key,
required this.onPressed,
required this.lable,
required this.backgroundColor,
this.textColor = Colors.black,
this.fontWeight = FontWeight.bold,
this.margin = EdgeInsets.zero})
: super(key: key);
#override
State<CustomButton> createState() => _CustomButtonState();
}
class _CustomButtonState extends State<CustomButton> {
bool isColorChanged = false;
#override
Widget build(BuildContext context) {
AppSize appSize = AppSize(context);
return GestureDetector(
onLongPress: () {
setState(() {
isColorChanged = true;
});
},
onLongPressCancel: () {
setState(() {
isColorChanged = false;
});
},
onTap: widget.onPressed,
child: Container(
margin: widget.margin,
height: isMobile(context) ? appSize.scaledHeight(0.065) : 80,
alignment: Alignment.center,
decoration: BoxDecoration(
color: isColorChanged
? Colors.transparent
: Color(widget.backgroundColor),
borderRadius: BorderRadius.all(Radius.circular(isMobile(context)
? 8
: 15) // <--- border radius here
),
border: Border.all(
color:
isColorChanged ? Color(themeColor) : Colors.transparent)),
padding: EdgeInsets.fromLTRB(20, 1, 20, 1),
child: Text(
widget.lable,
style: TextStyle(
fontSize: isMobile(context)
? MyFontSize().mediumTextSizeMobile
: MyFontSize().mediumTextSizeTablet,
color: widget.textColor,
fontWeight: widget.fontWeight),
),
// child:
),
);
}
}
Using Button :
class ExampleView extends StatelessWidget {
const ExampleView({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CustomButton(
onPressed: () {},
lable: StringFile.service_provider.toUpperCase(),
backgroundColor: colorYellowBtn),
),
);
}
}
before :
while we press the button:
when we release the button :
You can create a custom widget and use GestureDetector (onTapDown, onTapUp events to change color) with AnimatedContainer (to animate the color)
Try below code hope its help to you.
Refer ElevatedButton
Refer MaterialStateProperty
ElevatedButton(
child: Text(
'Service Provider'.toUpperCase(),
style: TextStyle(
color: Colors.black,
),
),
onPressed: () {
print('Pressed');
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) return Colors.teal;
return Colors.yellow;
},
),
),
),
After and before pressed result->
when you pressed the button result->
Try this :
RaisedButton(
onPressed: () {},
child: Text("Test"),
highlightColor: YOUR_PRESSED_COLOR, //Replace with actual colors
color: IDLE_STATE_COLOR,
),
ElevatedButton(
child: Text('Elevated Button', style: TextStyle(color: Colors.black),),
onPressed: () {
},
style: ButtonStyle(
backgroundColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) return Colors.white;
return Colors.yellow;
},
),
),
)
You can use like this.
I have a simple website menu on clicking it's just changing int value and on the basis of int value it's changing the font color.
I don't want to use setState instead of it I need to use getX I am doing it like this
class SideMenu extends StatefulWidget {
const SideMenu({Key? key}) : super(key: key);
#override
_SideMenuState createState() => _SideMenuState();
}
class _SideMenuState extends State<SideMenu> {
TileColorX tcx = Get.put(TileColorX());
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: [
DrawerHeader(
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Dashboard ',
style: Theme.of(context).textTheme.caption!.copyWith(
color: Colors.white,
fontSize: 21,
fontWeight: FontWeight.w700)),
Text('Dashboard',
style: Theme.of(context).textTheme.caption!.copyWith(
color: primaryColor,
fontSize: 21,
fontWeight: FontWeight.w700)),
],
)),
),
DrawerListTile(
title: "Dashboard",
svgSrc: "assets/icons/menu_dashbord.svg",
control: 0,
press: () {
tcx.toggle(0);
},
),
DrawerListTile(
title: "POS and Invoices",
svgSrc: "assets/icons/menu_tran.svg",
control: 1,
press: () {
tcx.toggle(1);
},
),
],
),
);
}
}
class DrawerListTile extends StatelessWidget {
DrawerListTile({
Key? key,
// For selecting those three line once press "Command+D"
required this.title,
required this.svgSrc,
required this.press,
required this.control,
}) : super(key: key);
final String title, svgSrc;
final VoidCallback press;
final int control;
TileColorX tcx = Get.put(TileColorX());
#override
Widget build(BuildContext context) {
return ListTile(
onTap: press,
horizontalTitleGap: 0.0,
leading: SvgPicture.asset(
svgSrc,
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54,
height: 16,
),
title: Text(
title,
style: TextStyle(
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54),
),
);
}
}
I have a class for toggle
class TileColorX extends GetxController {
RxInt selectedIndex = 0.obs;
void toggle(int index) => selectedIndex.value = index;
}
But it's not changing the state (mean not changing my font color)
You need to use Obx on that widget you want to see change. This will work
return Obx(() => ListTile(
onTap: press,
horizontalTitleGap: 0.0,
leading: SvgPicture.asset(
svgSrc,
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54,
height: 16,
),
title: Text(
title,
style: TextStyle(
color: control == tcx.selectedIndex.value
? Colors.white
: Colors.white54),
),
));
I don't know more detailed answer to what Obx exactly did but it will work for you :D
I'm trying to create a custom Alert dialogue using this package rflutter_alert . But when return the Alert it gives me this error
The argument type 'Future<bool?>' can't be assigned to the parameter type 'Widget?'.
Update:
here i created a custom widget of dialogue
class DialogueTwoButton extends StatelessWidget {
DialogueTwoButton(
{Key? key,
context,
required this.text1,
required this.text2,
required this.onpres1,
required this.onpress2})
: super(key: key);
final String text1;
final String text2;
final Function onpres1;
final Function onpress2;
#override
Widget build(BuildContext context) {
return _onAlertButtonsPressed(context, text1, text2, onpres1, onpress2);
}
var alertStyle = AlertStyle(
animationType: AnimationType.fromTop,
isCloseButton: false,
isOverlayTapDismiss: false,
descStyle: GoogleFonts.montserrat(color: Colors.black, fontSize: 18),
titleStyle: GoogleFonts.montserrat(
color: Colors.red,
),
);
_onAlertButtonsPressed(context, desc, title, onPressYes, onPressNo) {
return Alert(
context: context,
style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressYes,
color: HexColor("#5344ed")),
DialogButton(
child: Text(
"No",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressNo,
color: HexColor("#5344ed"),
)
],
).show(); // here need to change
}
and here is my other file where i'm creating a button
updateProduct() {
DialogueTwoButton(
onpres1: () {},
onpress2: () {},
text1: 'df',
text2: 'dsf',
);
bottomButton(context, () {
updateProduct();
}, "Update Product"),
and updateProduct(); on this mehtod calling the custom class dialogue, but it's not showing , i want to do this something in this way.
please help how to do this.
you missing one closing ) bracket after ).show()
_onAlertButtonsPressed(context,desc,title,onPressYes,onPressNo) {
return Alert(
context: context,
style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressYes,
color: HexColor("#5344ed")),
DialogButton(
child: Text(
"No",
style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressNo,
color: HexColor("#5344ed"),
)
],
).show(); // here need to change
}
Complete src code:
import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyHomePage(),
),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
TextEditingController _textEditingController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("title"),
),
body: Column(
children: [
InkWell(onTap: (){
_onAlertButtonsPressed(context,"test","title",(){},(){});
}, child: Text("test")),
],
),
);
}
}
_onAlertButtonsPressed(context,String desc,String title,onPressYes,onPressNo) {
return Alert(
context: context,
//style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
//style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressYes,
//color: HexColor("#5344ed")
),
DialogButton(
child: Text(
"No",
// style: GoogleFonts.montserrat(color: Colors.white, fontSize: 18),
),
onPressed: onPressNo,
// color: HexColor("#5344ed"),
)
],
).show(); // here need to change
}
Try below code hope its helpful to you. remove Container and Widget
onAlertButtonsPressed(context, desc, title, onPressYes, onPressNo) {
return Alert(
context: context,
style: alertStyle,
title: title,
desc: desc,
buttons: [
DialogButton(
child: Text(
"Yes",
),
onPressed: onPressYes,
),
DialogButton(
child: Text(
"No",
),
onPressed: onPressNo,
)
],
).show();
}
I am trying to implement this custom slider on my flutter app. I have searched most of the open source libraries but I cannot seem to get the one that suits my need.
The closet I got to is Cupertino Slider but I couldn't customize it to fit my need. Any ideas?
this is what you are looking for, slider_button:
SliderButton(
action: () {
///Do something here OnSlide
},
///Put label over here
label: Text(
"Slide to cancel !",
style: TextStyle(
color: Color(0xff4a4a4a),
fontWeight: FontWeight.w500,
fontSize: 17),
),
icon: Center(
child: Icon(
Icons.power_settings_new,
color: Colors.white,
size: 40.0,
semanticLabel: 'Text to announce in accessibility modes',
)),
///Change All the color and size from here.
width: 230,
radius: 10,
buttonColor: Color(0xffd60000),
backgroundColor: Color(0xff534bae),
highlightedColor: Colors.white,
baseColor: Colors.red,
);
Try this:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
class View extends StatefulWidget {
const View({Key? key}) : super(key: key);
#override
_ViewState createState() => _ViewState();
}
class _ViewState extends State<View> {
int segmentedControlGroupValue = 0;
final Map<int, Widget> myTabs = const <int, Widget>{
0: Icon(Icons.arrow_forward, color: Colors.white,),
1: Text("Start Shopping", style: TextStyle(color: Colors.orange),)
};
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CupertinoSlidingSegmentedControl(
backgroundColor: Colors.orange.withOpacity(0.2),
groupValue: segmentedControlGroupValue,
thumbColor: CupertinoColors.activeOrange,
children: myTabs,
onValueChanged: (newValue) {
setState(() {
segmentedControlGroupValue = newValue as int;
});
}),
),
);
}
}
I've created an app that "almost done", but there is some issue regarding to switching theme. I'm using getx and get_storage for it's state management.
I also using a lot of static type for themes because I think it should never get rebuilt all over the time. It works fine for the other components but not for texts. It acts like this which is kinda weird..
I have no idea what causing this, should I avoid using static classes for themes?
Please have a look at my script and feel free to tell me if I did something wrong.
main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await GetStorage.init();
...
...
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final box = GetStorage();
#override
Widget build(BuildContext context) {
return SimpleBuilder(
builder: (_) {
bool isDark = box.read('darkMode');
return GetMaterialApp(
...
theme: CustomTheme.light,
darkTheme: CustomTheme.dark,
themeMode: isDark == null
? ThemeMode.system
: isDark ? ThemeMode.dark : ThemeMode.light,
...
);
},
);
}
}
custom_theme.dart
class CustomTheme {
static ThemeData get light {
return ThemeData.light().copyWith(
...
cardTheme: CustomCardTheme.shared,
textTheme: CustomTextTheme.light,
...
);
}
static ThemeData get dark {
return ThemeData.dark().copyWith(
...
cardTheme: CustomCardTheme.shared,
textTheme: CustomTextTheme.dark,
...
);
}
}
card_theme.dart
class CustomCardTheme {
static CardTheme get shared {
return CardTheme(
elevation: 8.0,
margin: const EdgeInsets.only(bottom: 8.0),
shadowColor: Colors.black26,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
);
}
}
text_theme.dart
const String _fontFamily = 'Nunito Sans';
const TextStyle _lightStyle = TextStyle(
color: Colors.black,
fontFamily: _fontFamily,
);
const TextStyle _darkStyle = TextStyle(
color: Colors.white,
fontFamily: _fontFamily,
);
class CustomTextTheme {
static TextTheme get light {
return ThemeData.light().textTheme.copyWith(
headline1: _lightStyle,
headline2: _lightStyle,
headline3: _lightStyle,
headline4: _lightStyle,
headline5: _lightStyle,
headline6: _lightStyle,
subtitle1: _lightStyle,
subtitle2: _lightStyle,
bodyText1: _lightStyle,
bodyText2: _lightStyle,
// caption: _secondaryStyle,
);
}
static TextTheme get dark {
return ThemeData.dark().textTheme.copyWith(
headline1: _darkStyle,
headline2: _darkStyle,
headline3: _darkStyle,
headline4: _darkStyle,
headline5: _darkStyle,
headline6: _darkStyle,
subtitle1: _darkStyle,
subtitle2: _darkStyle,
bodyText1: _darkStyle,
bodyText2: _darkStyle,
// caption: _secondaryStyle,
);
}
}
profile_menu_card.dart
class ProfileMenuCard extends GetView<ProfileController> {
const ProfileMenuCard({
Key key,
this.iconBackgroundColor,
this.iconHeight = 18.0,
this.iconWidth = 18.0,
this.trailing,
#required this.label,
#required this.icon,
#required this.onTap,
}) : super(key: key);
final Color iconBackgroundColor;
final String label;
final String icon;
final double iconHeight;
final double iconWidth;
final VoidCallback onTap;
final Widget trailing;
#override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: ListTile(
onTap: onTap,
contentPadding: EdgeInsets.zero,
leading: Container(
height: 32,
width: 32,
decoration: BoxDecoration(
color: iconBackgroundColor ?? Get.theme.primaryColor,
borderRadius: BorderRadius.circular(10.0),
),
child: Center(
child: SvgPicture.asset(
icon,
height: iconHeight,
width: iconWidth,
),
),
),
title: Text(
StringUtils.capitalize(label, allWords: true),
style: Get.textTheme.bodyText1.copyWith(
fontWeight: FontWeight.w600,
),
),
trailing: trailing ?? Icon(Icons.chevron_right),
),
),
);
}
}
dark_mode_switch.dart
class DarkModeSwitch extends StatelessWidget {
final box = GetStorage();
#override
Widget build(BuildContext context) {
bool isDark = box.read('darkMode');
return Transform.scale(
scale: 0.8,
child: CupertinoSwitch(
value: isDark,
onChanged: (bool val) => box.write('darkMode', val),
),
);
}
}
profile_page.dart
const EdgeInsets _titlePadding = EdgeInsets.only(bottom: 10.0, left: 8.0);
class ProfilePage extends GetView<ProfileController> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SingleChildScrollView(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ListViewGroup(
title: Padding(
padding: _titlePadding,
child: Text('account.info'.tr, style: Get.textTheme.caption),
),
items: [
ProfileMenuCard(
icon: 'assets/icons/icon-user-circle.svg',
label: 'Personal',
onTap: () => Get.toNamed(Routes.ACCOUNT_INFO_PERSONAL),
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFFF3548D),
icon: 'assets/icons/icon-id-badge.svg',
label: 'Employment',
onTap: () {
// Get.toNamed(Routes.EMPLOYMENT_INFO);
},
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFF9A5BFF),
icon: 'assets/icons/icon-contacts.svg',
label: 'Contacts',
onTap: () => Get.toNamed(Routes.CONTACT_INFO),
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFF00D166),
icon: 'assets/icons/icon-book-reader.svg',
label: 'Educations',
onTap: () => Get.toNamed(Routes.EDUCATION_INFO),
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFF57109F),
icon: 'assets/icons/icon-briefcase.svg',
iconHeight: 15.75,
label: 'Working Experiences',
onTap: () => Get.toNamed(Routes.EXPERIENCE_INFO),
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFF28CEE8),
icon: 'assets/icons/icon-credit-card.svg',
iconWidth: 18,
iconHeight: 14,
label: 'Payroll',
onTap: () {},
),
],
),
ListViewGroup(
title: Padding(
padding: _titlePadding,
child: Text('settings'.tr, style: Get.textTheme.caption),
),
items: [
ProfileMenuCard(
iconBackgroundColor: Color(0xFF2DB9B0),
icon: 'assets/icons/icon-bell.svg',
label: 'Notifications',
onTap: () {},
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFF555D5C),
icon: 'assets/icons/icon-moon.svg',
label: 'Dark Mode',
trailing: DarkModeSwitch(),
onTap: null,
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFFFF894B),
icon: 'assets/icons/icon-paint.svg',
label: 'Color Scheme',
onTap: () {},
),
],
),
ListViewGroup(
title: Padding(
padding: _titlePadding,
child: Text('settings.others'.tr, style: Get.textTheme.caption),
),
items: [
ProfileMenuCard(
icon: 'assets/icons/icon-book.svg',
label: 'Official Documentation',
onTap: () {},
),
ProfileMenuCard(
iconBackgroundColor: Color(0xFF9D99B9),
icon: 'assets/icons/icon-info.svg',
label: 'About this app',
onTap: () {},
),
],
),
],
),
),
);
}
}
Themes in Flutter are managed by InheritedWidget ( Theme.of(context) ) to rebuild the Widget that's consuming it's values, much like MediaQuery or Localization... same situation applies, u need to "invalidate" the current context.
You can use static values for fonts, colors, images, whatever... I would use them, as it's more clear to me to build the styles by hand that trying to make sense of all the properties in ThemeData. Although, when u do it that way, you lose the transitions capabilities that Themes has by default to interpolate the values.
Anyway, if you are using GetX, just add at the beginning of each Widget you wanna rebuild on Theme change.
build(context){
context.theme; /// this
return ...
}
Here's a gist and the demo I made a while ago.