Check for color during widget test? - flutter

The goal is to verify the color of a RaisedButton.icon
During my widget tests, I have the ability to look for text with find.text as well as icons with find.byIcon. There is no built in method for finding color.
How does one do the equivalent of find.color?
And example of my code is
RaisedButton.icon(
color: Color(_isAttendingEvent ? 0xFFD9FFB3 : 0xFFE3FFC7),
icon: Icon(_isAttendingEvent ? Icons.star : Icons.star_border),
label: Text(
_isAttendingEvent ? 'Attending' : 'Attend',
),
),
I'm trying to determine whether there is color: Color(0xFFD9FFB3) or color: Color(0xFFE3FFC7)
And I'm not sure if this is possible

I am not sure with RaisedButton.icon, but if it is just an icon you can try using:
expect((tester.firstWidget(find.byType(Icon)) as Icon).color, Color(0xFFE3FFC7));
If it not the first icon widget that appears on your screen, you can specific an index of it by:
expect((tester.widget(find.byType(Icon).at(/*index*/)) as Icon).color, Color(0xFFE3FFC7));
Note: To find a widget colour, you need to cast that widget to be something that contain a color property
For example:
To find Material color you can use:
expect((tester.firstWidget(find.byType(Material)) as Material).color, Colors.black);
To find Container with BoxDecoration color:
expect(((tester.firstWidget(find.byType(Container)) as Container).decoration
as BoxDecoration).color, Colors.black);
To find Text color:
expect(((tester.firstWidget(find.text('text')) as Text).style).color, Colors.black);

To find Appbar Material. color
final appbar = tester.widget<AppBar>(find.byKey(Key("appbar")));
expect(appbar.backgroundColor,Colors.white);
To find Text color Material
final text = tester.widget<Text>(find.text("text"));
expect(text.style.color, Colors.grey);
expect(text.style.fontSize, 15);

Update you flutter version. It's working now, i am able to access color in widget test. My current flutter version is "Flutter 1.15.18 • channel dev".
Earlier it was not working with version "Flutter v1.12.13+hotfix.5"
Hope this will help. More details here

If you're using a TextButton, ElevatedButton, or Outlined button, the background color will be a MaterialStateProperty. You can verify the color in almost the same way as mentioned above:
expect(
tester.widget(textButton.first),
isA<TextButton>().having(
(w) => w.style?.backgroundColor?.resolve({}),
'button color',
Colors.grey,
));

Related

SlideAction Icon color need to change - Flutter

Using below package in Flutter :
https://pub.dev/packages/flutter_slidable/example
There in code you will find below widget:
SlidableAction(
onPressed: doNothing,
backgroundColor: Color(0xFF0392CF),
foregroundColor: Colors.white,
icon: Icons.save,
label: 'Save',
),
Now Please note that icon property has Icons.save which is inbuilt and coming from flutter inbuilt sdk package.
Now, I want to change the color of that Icon. I have tried using Icons() widget but it only accept Icons.any_inbuild_icon name as a value.
How can I change the color of that Slidable Icon? Thanks in advance.
foregroundColor is the color of the icon. so change the value of foreground and it works for me.
foregroundColor: Colors.white,
CHANGE TO WHATEVER COLOR YOU WANT
example:
Colors.red or pass hex value Color(0xDE00FF00)
VIEW CODE
VIEW RESULT

Is there a way to change the outline border color of the OTP fields using PinCodeTextField plugin

I'm new to Flutter. I'm using PinCodeTextField https://pub.dev/packages/pin_code_fields plugin to create OTP Text field I want the text field to be in different color but I couldn't find the decoration property to change the colour.
Spent hours looking for the same problem and finaly found a way around.
Searck for a file ‘otp_field_style.dart’ through find.
Open the file and you will see following:
import 'package:flutter/material.dart';
import 'package:<myApp’s Constants>/constants/constants.dart';
class OtpFieldStyle {
/// The background color for outlined box.
final Color backgroundColor;
/// The border color text field.
final Color borderColor;
/// The border color of text field when in focus.
final Color focusBorderColor;
/// The border color of text field when disabled.
final Color disabledBorderColor;
/// The border color of text field when in focus.
final Color enabledBorderColor;
/// The border color of text field when disabled.
final Color errorBorderColor;
OtpFieldStyle(
{this.backgroundColor: kFillShade7,
this.borderColor: kOrange4,
this.focusBorderColor: kOrange1,
this.disabledBorderColor: kFillShade4,
this.enabledBorderColor: kFillShade2,
this.errorBorderColor: Colors.red});
}
Now, you can change the colors by giving the hard values,
OR
Import your constants.dart file (where one normally defines the constants, including colors etc) in this and link the colors through it e.g,
import 'package:/constants/constants.dart';
is my contants file, I have linked my kColors in above code,
just change it to appropriate link for your constants dart file.
5. Save and close ‘otp_field_style.dart’.
You can change the colors through your defined constants, I hope it helps!
you can use this properties to change the colors
pinTheme: PinTheme(
shape: PinCodeFieldShape.box,
borderRadius: BorderRadius.circular(5),
fieldHeight: 50,
fieldWidth: 40,
activeFillColor: Colors.black,
inactiveColor: Colors.deepOrange,
inactiveFillColor: Colors.green,
selectedFillColor: Colors.deepPurple,
selectedColor: Colors.greenAccent,
activeColor: Colors.blue
),

Flutter: How do you set the text color for a ListTile that is 'selected'?

I am working on a Flutter app where I am using a drawer. The drawer consists of various menu options using the ListTile class. The documentation specifies that when the 'selected' property of a ListTile is true then 'By default the selected color is the theme's primary color.' but it makes no mention of the text color. Whenever a ListTile is selected the corresponding text changes to blue, which goes against my theme. How do I set the text color for a selected ListTile?
Thanks.
You can apply theme to ListTile by wrapping it with ListTileTheme.
ListTileTheme(
selectedColor: Colors.red, // text & icon color
selectedTileColor: Colors.green, // background color
child: ListTile(
title: Text('cats')
)
)

Flutter - how to get AppBar title foreground color

I have a Flutter app, where on the appBar, I have added a dropdown button. My app supports primary / secondary color changing.
The screenshot below shows an appBar for two different primary colors.
As you can see, the Flutter is able to decide what color to use for app bar text to keep proper readability - white for dark color and black for light color (second app bar).
I would like to set dropdown items' text color identical for the one, used by Flutter app bar text, hence, I would like to retrieve it.
Looking at Theme.of(context) properties, however, didn't give me a clue what color should I use to achieve what I need to.
Below is the code snippet:
final ThemeData _theme = Theme.of(context);
final int index = values.indexWhere((TimeSpan element) => element.value == initialValue.value);
return Theme(
data: _theme.copyWith(
canvasColor: _theme.primaryColor,
brightness: Brightness.dark,
),
child: DropdownButtonHideUnderline(
child: DropdownButton<TimeSpan>(
items: values
.map(
(value) => DropdownMenuItem(
child: Text(
value.toString(),
style: TextStyle(color: _theme.colorScheme.surface),
),
value: value,
),
)
.toList(),
onChanged: callback,
isExpanded: false,
value: values[index],
),
),
);
After a couple of days working with light / dark theme brightness, I figure out, a (possible) solution for the above case.
You can get the desired text color via one of the existing text themes, for instance Theme.of(context).primaryTextTheme.title.color returns color adjusted to current theme brightness.
Flutter renders the widget based on the final theme values it has.
So for example if the child widget has a different theme and the parent widget has a different theme, Flutter's rendering engine will first give preference to the child widget's theme over the parent widget's theme.
So DropdownButton has a theme hardcoded by default which cannot be directly changed as the widget does not accept any parameter to change the theme of the underlying widget(s) and as a result the Theme of the parent widget won't change/alter the theme of DropdownButton. That's the reason why the text Week remains black in both the cases.
If you really want to change the theme you can either alter the source code of DropDownButton or make a custom widget for it. However, simply hardcoding the values for text-color should still do the work.
In order to change the Appbar's text color you will have to manually change the text color as the parent theme suggests that the text color should be white whereas you want it to be black(as per your requirements).
Scaffold(
appBar: AppBar(
title: Text("Weight Overview",color: Colors.black)
)
[...]
)
On OP's request,
You can manually change the Theme of your children at any point of your Widget tree by using the Theme widget and providing it with a theme.
Solution code:
Scaffold(
appBar: AppBar(
title: Theme(
theme: ThemeData(primaryColor: Colors.black),
child: Text("Weight Overview",),
),
),
[...]
)

Flutter - Color name string to material color

In Flutter is there a way to generate a material color from it's name, without creating a full map Map<String,MaterialColor>.
In theory, something like this:
String colorName = "deepOrange";
MaterialColor color = Colors(colorName);
According to the comment, the intention is to save and read back from shared_preferences. In that case, it is better to save and retrieve the color by int value, not by string name, to ensure we always get the color.
Save: prefs.setInt("prefered_color", Color.value)
Retrieve: Color c = const Color(prefs.getInt('prefered_color') ?? 0xFF42A5F5);
According to the official doc, there's currently no API to perform the function you described. Although it's easy to implement your methodology, I doubt its usefulness in general cases. Also we have to deal with typos or noSuchColor errors. But using const / enum will offer the advantage of compile time error checking.
I manage to do something like that using the
Colors.primaries list ( found in the colors.dart file):
//colors.dart
/// The material design primary color swatches, excluding grey.
static const List<MaterialColor> primaries = <MaterialColor>[
red,
pink,
purple,
deepPurple,
indigo,
blue,
lightBlue,
cyan,
teal,
green,
lightGreen,
lime,
yellow,
amber,
orange,
deepOrange,
brown,
// The grey swatch is intentionally omitted because when picking a color
// randomly from this list to colorize an application, picking grey suddenly
// makes the app look disabled.
blueGrey,
];
So in order to save the colors:
Color colorToSave = Colors.indigo;
prefs.setInt("colorIndex", Colors.primaries.indexOf(colorToSave));
To retrieve:
MaterialColor colorSaved = Colors.primaries(getInt('colorIndex') ?? 0);
Hope that helps you.
Here is an easy way to do it.
Let's suppose you want to get the material color for Colors.blue
You can use this to get it:-
MaterialStateProperty.all(Colors.blue)
For example, to set the background color of an elevated button, a material color should be provided. You can provide a named color like:-
ElevatedButton(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
onPressed: (){},
child: Text('Press me'),
),
Hope helps.