Set state for a button in a ListView - flutter

I have an input page to create a new reminder. On this page you will select several different variables (reminder type, start date, etc.) - at this stage I am just trying to get it work for two variables.
I have a button object that I create, which takes some text, a "isSelected" value (which changes the color to show it is selected) and an onPress callback. The plan is to use a loop to create one of these buttons for each of the necessary selection options and then feed that into a ListView, so you have a scroll-able list of selection option. As you select the item the properties of the new reminder object will update and the color will change to selected.
When I click the button, the value is selected (the print statement shows this) but the button does not change to the new isSelected value, despite a SetState being used. What is it I am missing here? Is it possible to feed buttons into a ListView like this and still have their state update? Or do you need to find another work around?
class AddReminder extends StatefulWidget {
#override
_AddReminderState createState() => _AddReminderState();
}
class _AddReminderState extends State<AddReminder> {
String addReminder = "";
Reminder newReminder = Reminder();
#override
List<Widget> getReminderTypesButton(
String selectionName, List selectionOptions, var reminderVariable) {
// create new list to add widgets to
List<Widget> selectionOptionsWidgets = [];
// loop through selection options and create buttons
for (String selection in selectionOptions) {
bool isSelectedValue = false;
selectionOptionsWidgets.add(
FullWidthButton(
text: selection,
isSelected: isSelectedValue,
onPress: () {
setState(() {
reminderVariable = selection;
isSelectedValue = true;
});
print(reminderVariable);
},
),
);
}
;
// return list of widgets
return selectionOptionsWidgets;
}
Widget build(BuildContext context) {
List<List<Widget>> newList = [
getReminderTypesButton("Type", reminderTypesList, newReminder.type),
getReminderTypesButton(
"Frequency", repeatFrequencyTypesList, newReminder.repeatFrequency)
];
List<Widget> widgetListUnwrap(List<List<Widget>> inputList) {
//takes list of list of widgets and converts to widget list (to feed into list view)
List<Widget> widgetsUnwrapped = [];
for (var mainList in inputList) {
for (var widgets in mainList) {
widgetsUnwrapped.add(widgets);
}
}
return widgetsUnwrapped;
}
return SafeArea(
child: Container(
color: Colors.white,
child: Column(
children: [
Hero(
tag: addReminder,
child: TopBarWithBack(
mainText: "New reminder",
onPress: () {
Navigator.pop(context);
},
)),
Expanded(
child: Container(
child: ListView(
children: widgetListUnwrap(newList),
shrinkWrap: true,
),
),
),
],
),
),
);
}
}
Here are the lists that I reference
List<String> reminderTypesList = [
"Appointment",
"Check-up",
"Other",
];
List<String> repeatFrequencyTypesList = [
"Never",
"Daily",
"Weekly",
"Monthly",
"Every 3 months",
"Every 6 months",
"Yearly",
];
List<List<String>> selectionOptions = [
reminderTypesList,
repeatFrequencyTypesList
];

The reason your state not changing is that every time you call setState(), the whole build function will run again. If you initiate a state (in this case isSelectedValue) within the build method (since the getReminderTypesButton() got called within the build), the code will run through the below line again and again, resetting the state to the initial value.
bool isSelectedValue = false;
This line will always set the isSelectedValue to false, no matter how many time you call setState.
In order to avoid this, you need to place the state outside of the build method, ideally in the FullWidthButton like this:
class FullWidthButton extends StatefulWidget {
const FullWidthButton({Key? key}) : super(key: key);
#override
_FullWidthButtonState createState() => _FullWidthButtonState();
}
class _FullWidthButtonState extends State<FullWidthButton> {
bool isSelectedValue = false;
#override
Widget build(BuildContext context) {
return InkWell(
onTap: () => setState(() => isSelectedValue = !isSelectedValue),
// ...other lines
);
}
}

Related

Flutter - Getx update screen only after hot reload

There are 3 buttons and I want to change the color of the clicked button when I click it.
I manage the _currentFilter variable using obx and change the _currentFilter value using the changeFilter() function every time I click the button.
And the UI section used Obx to detect the changed value and change the color.
However, clicking each button changes the value of _currentFilter, but does not update the UI.
Only Hot Reload will change the color of the button text.
Why doesn't Obx detect that the _currentFilter value has changed in the UI?
I don't know why it is reflected in the UI only when doing Hot Reload.
Please Help.
UI
class FilterButtons extends GetView<TodoController> {
const FilterButtons({Key? key}) : super(key: key);
Widget filterButton(FilterEnum filter) {
return TextButton(
onPressed: () => controller.changeFilter(filter),
child: Obx(() {
final color = controller.filter == filter ? Colors.blueAccent : Colors.grey;
return Text(filter.name, style: TextStyle(fontSize: 20, color: color));
}),
);
}
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
filterButton(FilterEnum.ALL),
filterButton(FilterEnum.ACTIVE),
filterButton(FilterEnum.COMPLETED),
],
);
}
}
Controller
class TodoController extends GetxController {
var _currentFilter = FilterEnum.ALL.obs;
get filter => _currentFilter;
void changeFilter(FilterEnum filter) {
_currentFilter = filter.obs;
}
}
if you assign new observable to _currentFilter, GetX won't get notified because previous observable that view is listening to didn't change.
if you change it to:
_currentFilter.value = filter;
GetX fires a method called refresh() that refreshes the view.

Flutter Expansion Pannel not Expanding without immutable bool

I have an expansion panel in _buildCategoryListings() that does not expand when the header or the dropdown button is clicked. isExpanded is set to the boolean categoryView.isExpanded. Through printing via the console I can see that the setState is actually updating the bool value but it looks like the actual widget isn't being redrawn perhaps? If I manually set isExpanded to true I see the results I want from the GUI. I also had set isExtended to theExpanded (which is in MovieListingView) which raises the issue of a mutable variable being in a class that extends StatefulWidget, this did give me the desired results though.
The question: How do I get the expansion panel to update the categoryView.isExpanded (via theListings[panelIndex].isExpanded) bool and show it via the GUI?
Thank you in advance.
Side note I thought about using a provider to keep track of this bool but that seems like overkill.
class MovieListingView extends StatefulWidget {
#override
_MovieListingView createState() => _MovieListingView();
MovieListingView(this.movieList);
final MovieCatalog movieList;
//bool theExpanded = false;
List<MovieCategoryView> generateCategoryList() {
List<MovieCategoryView> tempList = [];
List<String> movieCategories = movieList.Categories;
movieCategories.forEach((category) {
MovieCategoryView categoryView = new MovieCategoryView(
movieCategoryName: category.toString(),
movieList: movieList.getMovieCardListByCategory(category));
tempList.add(categoryView);
});
return tempList;
}
}
class _MovieListingView extends State<MovieListingView> {
Widget build(BuildContext context) {
// TODO: implement build
return SingleChildScrollView(
physics: ScrollPhysics(),
padding: EdgeInsets.all(5.0),
child: _buildCategoryListings(),
);
}
List<MovieCategoryView> generateCategoryList() {
List<MovieCategoryView> tempList = [];
List<String> movieCategories = widget.movieList.Categories;
int counter = 0;
movieCategories.forEach((category) {
MovieCategoryView categoryView = new MovieCategoryView(
movieCategoryName: category.toString(),
movieList:
widget.movieList.getMenuItemCardListByCategory(category),
isExpanded: false);
tempList.add(categoryView);
});
return tempList;
}
Widget _buildCategoryListings() {
final List<MovieCategoryView> theListings = generateCategoryList();
return ExpansionPanelList(
expansionCallback: (panelIndex, isExpanded) {
setState(() {
theListings[panelIndex].isExpanded = !isExpanded;
//widget.theExpanded = !isExpanded;
});
},
children: theListings.map((MovieCategoryView movieCategoryView) {
return ExpansionPanel(
canTapOnHeader: true,
headerBuilder: (BuildContext context, bool isExpanded) {
return ListTile(
title: Text(movieCategoryView.movieCategoryName),
);
},
body: Column(
children: movieCategoryView.movieList,
),
isExpanded: movieCategoryView.isExpanded);
}).toList(),
);
}
}
class MovieCategoryView {
MovieCategoryView(
{#required this.movieCategoryName,
#required this.movieList,
this.isExpanded});
String movieCategoryName;
List<MovieCard> movieList;
bool isExpanded = false;
}
This is happening because whenever the setstate() is called whole widget tree is rebuild and thus when you try changing the isexpandable value ,is gets changed but the
function generateCategoryList(); again gets called and generates the previous list again and again.
Widget _buildCategoryListings() {
final List<MovieCategoryView> theListings = generateCategoryList();
To fix this call the generateCategoryList(); once in initState() and remove the line above line.

flutter TabBarView sometimes not triggering on gesture swipe

I am using Flutter -Android studio. I have main screen with TabBarView control (2 pages). each page get data from sqfite database. both have same statefull widget class, but I pass parameter to look into database and display.
Issue : when I click tabbar header , data displayed is Ok. But when I swipe tabs, it sometimes work and sometimes does not work. as per below video. I have check and seems that Build event is not trigger every if Swipe was done.
Main widget with tabbarview
screen record
Note that 1st tab has only 1 record, while second has 6 records. tabClick works fine, but swipe sometime not work properly.
body: TabBarView(
controller: _tabController,
children: [
DisplayTransactions(
tmptransType: TransactionType.enIncome,
transacBloc: _transacBloc,
SelectedItemsCount: bRowSelectionCount,
onSelectionChanged: (count) {
setState(() {
bRowSelectionCount = count;
});
},
),
// Center(child: Text("Page 1")),
DisplayTransactions(
tmptransType: TransactionType.enExpense,
transacBloc: _transacBloc,
SelectedItemsCount: bRowSelectionCount,
onSelectionChanged: (count) {
setState(() {
bRowSelectionCount = count;
});
},
//Center(child: Text("Page 2")),
)
],
),
------ > Widget to display data into listview for each tabbar page
class DisplayTransactions extends StatefulWidget {
final TransactionType tmptransType;
final FinanceTransBlock transacBloc;
final Function onSelectionChanged;
int SelectedItemsCount;
/// -1 expense 1 income
DisplayTransactions(
{Key key,
#required this.tmptransType,
#required this.transacBloc,
this.SelectedItemsCount,
this.onSelectionChanged})
: super(key: key);
#override
_DisplayTransactionsState createState() => _DisplayTransactionsState();
}
class _DisplayTransactionsState extends State<DisplayTransactions> {
var isSelected = false;
var mycolor = Colors.white;
// int iselectionCount = 0;
#override
Widget build(BuildContext context) {
widget.transacBloc.transacType = widget.tmptransType;
debugPrint("----------------------------- ${widget.tmptransType}");
if (widget.SelectedItemsCount == 0) {// if no rows selected, then reload database based on trans type, eg expense, or income.. etc
widget.transacBloc.refresh();
}
return StreamBuilder<List<FinanceTransaction>>(
stream: widget.transacBloc.transacations,
builder: (context, snapshot) {
if (snapshot.hasData) {
List<FinanceTransaction> list = snapshot.data;
// return buildTaskListWal(snapshot.data);
return Padding(
It looks like the app is taking some time to retrieve the new data. Try checking for null on the snapshot.data and display a circularProgressIndicator.
if (snapshot.data == null) {
return CirgularProgressIndicator();
} else {
//display data
}

changing a nested child fields from its parent in flutter?

I have a widget A that has a nested widget B. I need to update a field on B (maybe by calling a function of B) when user click on a button in A. How can I do it?
EDIT: more details
Widget B is a widget that I use across my app so I want to leave him as a separate widget. Widget A is composed of widget B plus another button and I want that click on the button will change the the text that inside Widget B
EDIT2 - what I want to achieve:
Widget B is actually a Container that contains TextFormField with some other widgets. I use it for 5 form fields. now I want to add a field for location. the field for location consists of B plus a list that open when user type and there are results from google geocode. When the user clicks on one of the results, I want to set the TextFormField controller text to the value the user type.
So, I don't want to copy all logic and widgets for the text field from B to A.
In my code widget B is FormTextField and A is LocationField
class LocationField extends StatefulWidget {
Location meetingPointData;
LocationField(this.meetingPointData): super();
#override
_LocationFieldFieldState createState() => new _LocationFieldFieldState();
}
class _LocationFieldFieldState extends State<LocationField> {
OverlayEntry _overlayEntry;
var addresses;
final LayerLink _layerLink = LayerLink();
#override
void initState() {
super.initState();
}
onLocationInputChanged(text) {
this.findLocations(text);
}
#override
Widget build(BuildContext context) {
return CompositedTransformTarget(
link: this._layerLink,
child: FormTextField('meetingPoint', 'Meeting Point', "", "enter the name of a place or an address", TextInputType.text, onLocationInputChanged, true , {"empty": "Please enter the meeting point"})
);
}
OverlayEntry _createOverlayEntry() {
RenderBox renderBox = context.findRenderObject();
var size = renderBox.size;
var addressesWidget = <Widget>[];
for(var i=0; i< addresses.length; i++) {
addressesWidget.add( ListTile(
title: Text(addresses[i].addressLine),
onTap: () {
widget.meetingPointData = Location(addresses[i].addressLine);
setState(() {});
this._overlayEntry.remove();
this._overlayEntry = null;
},
),);
}
return OverlayEntry(
builder: (context) => Positioned(
width: size.width,
child: CompositedTransformFollower(
link: this._layerLink,
showWhenUnlinked: false,
offset: Offset(10.0, size.height - 45.0),
child: Material(
elevation: 4.0,
child: ListView(
padding: EdgeInsets.zero,
shrinkWrap: true,
children: addressesWidget
),
),
),
)
);
}
Future findLocations(text) async {
if(text == "") {
addresses = [];
return;
}
// From a query
final query = text;
try {
addresses = await Geocoder.local.findAddressesFromQuery(query);
var first = addresses.first;
print("${first.featureName} : ${first.coordinates}");
} catch (err) {
}
if(addresses.length > 0) {
if(this._overlayEntry != null) {
this._overlayEntry.remove();
this._overlayEntry = null;
}
this._overlayEntry = this._createOverlayEntry();
Overlay.of(context).insert(this._overlayEntry);
} else {
}
}
}
Assuming that the widget tree you're thinking of is:
A(
child: B(),
);
Then A should not be able to modify the state of B. Even if it is technically possible through global variables/GlobalKey, it is anti-pattern to do so.
Instead, you should move the state up in the tree and store your field inside A instead of B.

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((){});
},
)