How to access/change an attribute of a Widget in Flutter - flutter

I have a Menu button that has 3 icons, and I want to hover the icon of the current page.
The code of the widget is:
class MenuButton extends StatelessWidget {
int current;
MenuButton({#required this.current}) {}
#override
Widget build(BuildContext context) {
Widget cirMenu = FabCircularMenu(
children: <Widget>[
IconButton(
icon: Image.asset('img/performance.png'),
onPressed: () {
print('Favorite');
}),
IconButton(
icon: Image.asset('img/shop.png'),
onPressed: () {
print('Home');
}),
IconButton(
icon: Image.asset('img/category.png'),
onPressed: () {
print('Favorite');
})
],
ringDiameter: 230,
ringWidth: 90,
animationCurve: Cubic(1, 1.65, .62, .83),
);
return cirMenu;
}
I would like to hover the image of the current page, but I don't know how to access the Widget attribute. The final functionality should be something like this (though it is not compiling), that is just adding a conditional to change the image:
if (current == 0) {
cirMenu.children[0].Icon = Image.asset('img/performance-hover.png');
}
if (current == 1) {
cirMenu.children[1].Icon = Image.asset('img/shop-hover.png');
}
if (current == 2) {
cirMenu.children[2].Icon = Image.asset('img/category-hover.png');
}
return cirMenu;
How can I accomplish that?

You can't modify properties of a widget once it's built. It's immutable. In other words you need to rebuild it every time that you want to change something about it.
One potential solution would be to modify your code to use proper background on each rebuild.
Image getBackground(int current) {
if (current == 0) {
return Image.asset('img/performance-hover.png');
}
if (current == 1) {
return Image.asset('img/shop-hover.png');
}
if (current == 2) {
return Image.asset('img/category-hover.png');
}
//handle other indices
}
Then depending on your desired outcome you can use this method when constructing MenuButton.
Remember - you don't need (or even can't) modify widget as it's built. The data (i.e. index or image) must flow from top to bottom of the widget tree.

if you just want a message you can use tooltip attribute that is already inside IconButton()
like this
IconButton(
icon: Image.asset('img/performance.png'),
onPressed: () {
print('Favorite');
}, tooltip: 'Favorite')
if you want a color change on hover you can change hoverColor attribute like this
IconButton(
icon: Image.asset('img/performance.png'),
onPressed: () {
print('Favorite');
}, hoverColor: Colors.red)

Related

How to call nested conditional void function with onPressed [flutter]

I have a customized flutter stepper widget and I want to having conditional back button when I press the backbutton in appbar, it will be back on previous step, just like this
onPressed: () {
if (currentStep != 0) {
onStepCancel;
} else {
Navigator.pop(context);
}
},
and somehow onStepCancel is can't be call because it has a value of final VoidCallback? onStepCancel, I put another function inside another function A.K.A nested, I want to use this widget in another class, so it can be simplify by only putting the void function inside onStepCancel
CustomStepper(
. . .
currentStep: controller.currentStep.value,
onStepContinue: controller.increment,
onStepCancel: controller.decrement,
);
the void function that fill with decrement function of currentStep will be proceed inside onStepCancel and when user click on back button with condition currentStep != 0 it will show the previous step and when user is reaching currentStep == 0 it will back to previous page Navigator.pop(context);, but the problem is onStepCancel can't be VoidCallback? because the conditional function is already the void function itself and it can't be returned VoidCallBack? inside it, so how can I call onStepCancel function inside conditional case with onPressed, this is the widget function where I put it:
Widget _buttonBack(int stepIndex, BuildContext context) {
return IconButton(
onPressed: () {
if (currentStep != 0) {
onStepCancel;
} else {
Navigator.pop(context);
}
},
icon: SvgPicture.asset(
Images.backArrowButton,
color: ColorResources.brandHeavy,
),
);
}
and I want to put Widget _buttonBack inside:
Scaffold(
appBar: AppBar(
. . .
leading: _buttonBack(currentStep, context),
. . .
);
edit:
onStepCancel is fullfil with void function that I call from controller:
void decrement() => currentStep--;
void decrement() is the function for getting back to previous Step and I call decrement() function in onStepCancel just like this:
onStepCancel: controller.decrement
Inside my CustomStepper class, onStepCancel will pass decrement to onPressed(), I have try few way to put conditional onPressed(), with this:
onPressed: () => currentStep != 0 ? onStepCancel : Navigator.pop(context),
and this
onPressed: () {
if (currentStep != 0) {
onStepCancel;
} else {
Navigator.pop(context);
}
},
both conditional doesn't work, but the funny thing is when I call onStepCancel without conditional case, like this:
onPressed: onStepCancel
it show no problem and it works well, so the point is, on step cancel will only work well without nested function, I only could call it with onStepCancel without any conditional function, how to call nested function? is it needed to be in any other form instead of function or else?
if onStepCancel is a callback, you should call it instead of returning it:
if (currentStep != 0) {
onStepCancel();
} else {
Navigator.pop(context);
}

UI not properly updating after moving element from List<Widget>

I have a List<Entry> mySet, which is a List of widget Entry.
In a parent widget, I use a ListView.builder to generate these widgets.
This parent widget has two additional methods
addEntry() {
setState(() {
mySet.add(Entry(index: mySet.length));
});
}
removeEntry(_EntryState entry) {
int index = entry.widget.index;
setState(() {
mySet.removeWhere((item) => item.index == index);
});
}
The buttons that call these in each entry look like this
IconButton(
iconSize: 25,
icon: Icon(Icons.add),
onPressed: index == mySet.last.index
? () {
setState(() {
pKey.currentState!.addEntry();
});
}
: null),
IconButton(
iconSize: 25,
icon: Icon(Icons.remove),
onPressed: isLast(() {
setState(() {
pKey.currentState!.removeEntry(this);
});
})),
And this function
isLast(Function fn) => index == mySet.last.index ? fn : null;
The condition on the add and subtract functions are identical, this was just me testing and trying to debug the problem.
The problem:
When I click to add a row widget, the prior rows' add/remove buttons are disabled, as they should be.
But when I click remove on the last row, the prior row's buttons are not re-enabled.
Yet if I make a small change to the code (anything), to trigger a hot-reload, the last row's buttons enable.
Here's my Listview.builder code, in the same parent widget.
#override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return mySet[index];
},
itemCount: mySet.length);
}
The user in question Flutter: The widget values ​inside the ListView are not updated when an item is removed has a similar problem.
In your case you can solve this issue by using a ValueKey(property) where property is a a ofttribute your Entry object which you are sure is different for every Entry.
Make sure no two Entries can have the same value for property at the same time as otherwise flutter will throw an Error as you will have two identical ValueKeys.
I solved part of the problem by having one array that tracked instances of Entry, and one array to track corresponding states.
I could then call setState() for the last item which was the source of my trouble in my post.
removeEntry(_Entry entry) {
theSetStates.removeWhere((v) => v == entry);
theSet.removeWhere((v) => v == entry.widget);
setState(() {});
theSetStates.last.setState(() {});
}
If there's an easier way to get a list of instances of a Widget. Please let me know. Google didn't turn up anything.

how to navigate to another page at else statement in flutter

I have a List of String stored in a variable like this:
var question = [
'whats your favorite name',
'whats your favorite color',
'whats your favorite shape',
];
And have function that increase a variable each time I call it
void _Press(){
setState((){
_PressedNo = _PressedNo + 1;
});
print(_PressedNo );
}
And in my scaffold iam checking if the _PressedNo is smaller that List so it rebuild the scaffold with the new question each time i press the button till the questions finished like this :
return MaterialApp(
home: Scaffold(
body:_PressedNo < question.length ? Container(
child: RaisedButton(
child: Text('yes'),
onPressed:() {
_Press();
},
),
) : // here i want to go to another page
And after the else : i want to go to another Flutter page, but I can only add widgets here so any solution how to do that..
You'll have to take a bit of a different approach. The build method should only provide things that appear on the screen and not directly trigger a specific action or state change, such as navigating to another page.
You can handle this in the _Press() method:
void _Press() {
if(_PressedNo < questions.length) {
setState(() {
_PressedNo = _PressedNo + 1;
});
} else {
Navigator.of(context).push(...); // navigate to another page
// optionally set the _PressedNo back to 0
setState(() {
_PressedNo = 0;
});
}
}
Your build method should not change, since on this page it should always show the same button.
return MaterialApp(
home: Scaffold(
body: Container(
child: RaisedButton(
child: Text('yes'),
onPressed:() {
_Press();
},
),
),
);
Some other pointers:
use lowerCase for functions and variables: _press() and _pressedNo.
You can directly pass in the function to onPressed like onPressed: _press, (note that there are no parentheses since the function is not called but just passed along)

How to use Provider to show or hide FAB?

I'm just starting to look at alternatives to setState() and therefore Provider. In the first program that I am looking at to implement Provider, the only setState() that I use is on the initial build(), and also when data changes in order to display a FAB when the FAB is not already displayed. There are six TextField widgets in this program, and they all have TextEditingControllers, so they all have their own state.
Is it feasible to use Provider in this situation when _tfDataHasChanged (bool) changes, and if so, how?
Code is below for the FAB creation:
Widget _createFab() {
if (_tfDisplayOnly || !_tfDataHasChanged) return null;
return FloatingActionButton(
onPressed: _btnSubmitPressed,
backgroundColor: _colorFab,
mini: false,
tooltip: _sBtnSubmitText /* Add or Create */,
child: _iconFab,
);
}
You can:
Widget _createFab( BuildContext context) {
boolean showFab = Provider.of<ShowFab>(context).shouldShow;
return showFab?FloatingActionButton(
onPressed: _btnSubmitPressed,
backgroundColor: _colorFab,
mini: false,
tooltip: _sBtnSubmitText /* Add or Create */,
child: _iconFab,
):null;
}
with the ShowFab class looking like
class ShowFab with ChangeNotifier {
boolean shouldShow;
void showFab( boolean show ){
shouldShow = show;
notifyListeners();
}
}
Obviously your specific logic will be different,
The ShowFab needs to be provided higher in the widget tree.
ChangeNotifierProvider<ShowFab>( builder: (context) => ShowFab(), child: .... )

setState does not seem to work inside a builder function

How does setState actually work?
It seems to not do what I expect it to do when the Widget which should have been rebuilt is built in a builder function. The current issue I have is with a ListView.builder and buttons inside an AlertDialog.
One of the buttons here is an "AutoClean" which will automatically remove certain items from the list show in the dialog.
Note: The objective here is to show a confirmation with a list of "Jobs" which will be submitted. The jobs are marked to show which ones appear to be invalid. The user can go Back to update the parameters, or press "Auto Clean" to remove the ones that are invalid.
The button onTap looks like this:
GeneralButton(
color: Colors.yellow,
label: 'Clear Overdue',
onTap: () {
print('Nr of jobs BEFORE: ${jobQueue.length}');
for (int i = jobQueue.length - 1; i >= 0; i--) {
print('Checking item at $i');
Map task = jobQueue[i];
if (cuttoffTime.isAfter(task['dt'])) {
print('Removing item $i');
setState(() { // NOT WORKING
jobQueue = List<Map<String, dynamic>>.from(jobQueue)
..removeAt(i); // THIS WORKS
});
}
}
print('Nr of jobs AFTER: ${jobQueue.length}');
updateTaskListState(); // NOT WORKING
print('New Task-list state: $taskListState');
},
),
Where jobQueue is used as the source for building the ListView.
updateTaskListState looks like this:
void updateTaskListState() {
DateTime cuttoffTime = DateTime.now().add(Duration(minutes: 10));
if (jobQueue.length == 0) {
setState(() {
taskListState = TaskListState.empty;
});
return;
}
bool allDone = true;
bool foundOverdue = false;
for (Map task in jobQueue) {
if (task['result'] == null) allDone = false;
if (cuttoffTime.isAfter(task['dt'])) foundOverdue = true;
}
if (allDone) {
setState(() {
taskListState = TaskListState.done;
});
return;
}
if (foundOverdue) {
setState(() {
taskListState = TaskListState.needsCleaning;
});
return;
}
setState(() {
taskListState = TaskListState.ready;
});
}
TaskListState is simply an enum used to decide whether the job queue is ready to be submitted.
The "Submit" button should become active once the taskListState is set to TaskListState.ready. The AlertDialog button row uses the taskListState for that like this:
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
if (taskListState == TaskListState.ready)
ConfirmButton(
onTap: (isValid && isOnlineNow)
? () {
postAllInstructions().then((_) {
updateTaskListState();
// navigateBack();
});
: null),
From the console output I can see that that is happening but it isn't working. It would appear to be related to the same issue.
I don't seem to have this kind of problem when I have all the widgets built using a simple widget tree inside of build. But in this case I'm not able to update the display of the dialog to show the new list without the removed items.
This post is getting long but the ListView builder, inside the AleryDialog, looks like this:
Flexible(
child: ListView.builder(
itemBuilder: (BuildContext context, int itemIndex) {
DateTime itemTime = jobQueue[itemIndex]['dt'];
bool isPastCutoff = itemTime.isBefore(cuttoffTime);
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Text(
userDateFormat.format(itemTime),
style: TextStyle(
color:
isPastCutoff ? Colors.deepOrangeAccent : Colors.blue,
),
),
Icon(
isPastCutoff ? Icons.warning : Icons.cached,
color: isPastCutoff ? Colors.red : Colors.green,
)
],
);
},
itemCount: jobQueue.length,
),
),
But since the Row() with buttons also doesn't react to setState I doubt that the problem lies within the builder function itself.
FWIW all the code, except for a few items like "GeneralButton" which is just a boilerplate widget, resides in the State class for the Screen.
My gut-feeling is that this is related to the fact that jobQueue is not passed to any of the widgets. The builder function refers to jobQueue[itemIndex], where it accesses the jobQueue attribute directly.
I might try to extract the AlertDialog into an external Widget. Doing so will mean that it can only access jobQueue if it is passed to the Widget's constructor....
Since you are writing that this is happening while using a dialog, this might be the cause of your problem:
https://api.flutter.dev/flutter/material/showDialog.html
The setState call inside your dialog therefore won't trigger the desired UI rebuild of the dialog content. As stated in the API a short and easy way to achieve a rebuild in another context would be to use the StatefulBuilder widget:
showDialog(
context: context,
builder: (dialogContext) {
return StatefulBuilder(
builder: (stateContext, setInnerState) {
// return your dialog widget - Rows in ListView in Container
...
// call it directly as part of onTap of a widget of yours or
// pass the setInnerState down to another widgets
setInnerState((){
...
})
}
);
EDIT
There are, as in almost every case in the programming world, various approaches to handle the setInnerState call to update the dialog UI. It highly depends on the general way of how you decided to manage data flow / management and logic separation. As an example I use your GeneralButton widget (assuming it is a StatefulWidget):
class GeneralButton extends StatefulWidget {
// all your parameters
...
// your custom onTap you provide as instantiated
final VoidCallback onTap;
GeneralButton({..., this.onTap});
#override
State<StatefulWidget> createState() => _GeneralButtonState();
}
class _GeneralButtonState extends State<GeneralButton> {
...
#override
Widget build(BuildContext context) {
// can be any widget acting as a button - Container, GestureRecognizer...
return MaterialButton(
...
onTap: {
// your button logic which has either been provided fully
// by the onTap parameter or has some fixed code which is
// being called every time
...
// finally calling the provided onTap function which has the
// setInnerState call!
widget.onTap();
},
);
}
If you have no fixed logic in your GeneralButton widget, you can write: onTap: widget.onTap
This would result in using your GeneralButton as follows:
...
GeneralButton(
...
onTap: {
// the desired actions like provided in your first post
...
// calling setInnerState to trigger the dialog UI rebuild
setInnerState((){});
},
)