changing variables inside listview builder - flutter

i want to change variable values when the widget is loading the data from the web,
just want to do something like this:
_playid = _notes[1].id;
title = _notes[1].title;
but wherever I put it, i get an error,
I tried to put it in a set state inside listview builder, but no luck since I don't want it with onPress or on tap methods
could someone help, please?

i just found out,
simply we have to use setstate in fetch inside initstate
void initState() {
title = " ";
fetchNotes().then((value) {
setState(() {
_notes.addAll(value);
_playid = _notes[0].numb;
});
});
}

Related

Dynamically added widget state is null in Flutter

I am developing a feature where users can press a button to add a new group of text fields to the screen. Each group of text fields is stored in its own stateful widget. The abridged code to add the new widget is shown below:
List<EducationField> fieldList = [];
List<GlobalKey<EducationFieldState>> keyList = [];
// Function that adds new widgets to the list view
onTap: () {
GlobalKey<EducationFieldState> key = new GlobalKey<EducationFieldState>();
setState(() {
fieldList.add(EducationField(key: key));
keyList.add(key);
});
},
I can dynamically add the new widgets just fine. However when I try to access the state of the widgets, I get an error saying that the state of the respective widget is null. There is a function in each widget state that gets the values from their text fields. The code I'm using to do that is also shown below:
void _getUserData(){
List<EducationModel> modelList = [];
for(int i = 0; i < fieldList.length; i++){
modelList.add(keyList[i].currentState!.getData()); // this line is causing the error
modelList.last.printModel();
}
}
I have done a lot of research on this issue and still have no idea why I am getting a null error. Is my approach wrong or is it something more minor? I can also give more code if necessary.
Thanks in advance!
Checkout GlobalKey docs.
Your dynamically added Text widget doesn't exist in the Widget tree yet, as you just created it and you're trying to add it to the Widget tree. So it doesn't have a current state.
Maybe this helps?
keyList[i].currentState?.getData() ?? '' // I'm guessing getData return a String
Something else you could try:
// only call _getUserData() after widget finished building
WidgetsBinding.instance!.addPostFramecallback(() => _getUserData());

Flutter. How to correctly update state of nested widgets?

I'm new in flutter and I'm trying to implement something like radio group with custom buttons in Android. For this I created StatefulWidget, which hold list of selectable buttons. For every button I was set press listener where I do something like this:
setState(() {
buttons.forEach((button) => button.isSelected = false);
buttons[selectedButtonIndex].isSelected = true;
});
And then my CustomButtonWidget changes color depending on the parameter isSelected .
All this works well. However, I have an additional requirement. I need my RadioGroupWidget to return the selected button type. For this I created a callback :
final ValueChanged<ButtonType> onChanged;
And now my button press listener looking like this:
onTap: () {
setState(() {
buttons.forEach((button) => button.isSelected = false);
buttons[selectedButtonIndex].isSelected = true;
});
onChanged(buttons[selectedButtonIndex].type);
}
Next I get this type of button in my other widget which is using RadioGroupWidget:
CustomRadioGroup(
onChanged: (value) {
setState(() {
buttonType= value;
});
}),
)
As you can see I call again setState. This is what leads to the problem. But I need to do this, because I need to update the state of another widget (for example let's call it InfoWidget) depending on the selected button.
After all these manipulations, the state of the InfoWidget is updated correctly, but the state of the selected button in the RadioGroupWidget does not change. I tried to debug this and I see that at first the parameter isSelected is set to true for the desired button, but after the state of the button I selected is not updated, because its parameter isSelected becomes false. And I don't understand why this is happening.
Please help, I am completely confused.

Api data null whe nthe pages load even i use initState

im using post method to get api data/response.body in initState and i get all the response/data then i put it in my variables surveyData, but when i load the pages with widget looped by the response.body length it goes error and say response.body.length is null but when i save the text editor/ hot reload, all the data entered and it's not null anymore and the widget appear.
fyi: the http.post method is my own function not from import 'package:http/http.dart' as http; so don't mind it
Variables that contain the response
dynamic surveyData;
initState Code
#override
void initState() {
super.initState();
// GET PAGES
surveyPages = widget.surveyPages;
// GET FORM DETAIL
http.post(
'survey-pre-mitsu/form-detail',
body: {
"survey_form_header_id": 1,
},
).then(
(res) {
surveyData = res['data'];
},
);
}
Widget that looped by surveyData.length
for (var i = 0; i < surveyData.length; i++)
AdditionalForm(questionLabel: surveyData[i]['label'],
questionType: surveyData[i]['type'],),
This is what the error
And this is what it looks like when i do hot reload
First, I suggest you to use future builder to resolve this problem.
First, I suggest performing post(even though its your own code) as a asynchronous operation, hence not inside initState(). Preferably write the logic in a separate class/file with packages like a provider package. Try this first and then post the error after that.
You need to add Some delay , In this Delay you can show a loading icon . for delay you can use :
Future.delayed(const Duration(milliseconds: 500), () {
// Here you can write your code
setState(() {
// Here you can write your code for open new view
});
});
This will solve your problem

Overwrite Paste Event for TextFormField

I have a TextFormField. Usually you can use the selection toolbar to copy/paste/select all and so on using long tap/double tap.
I want to overwrite the Paste Event. It shouldn't simple insert the current clipboard data but open a popup with several options to insert.
Is it possible to catch and overwrite the Paste event in any way? I saw something like handlePaste() for SelectionControls, but I don't know how to add this to my TextFormField.
Thanks in advance!
AFAIK, you can't exactly 'intercept' the standard toolbar. However, what you can do is to prevent the standard toolbar and make your own.
You can use wrap the textfield/textformfield under IgnorePointer. It will hide any tap gestures on the text field. Below is the code snippet.
IgnorePointer(
child: TextField(
focusNode: _textfieldFocusNode,
controller: _controller,
),
)
Now,you can wrap this IgnorePointer under GestureDetector and show your own menu. Like this :
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
FocusScope.of(context).requestFocus(_textfieldFocusNode);
},
onLongPress: () {
showMenu(____
}
)
This produces the result below and the sample implementation code is here
Found a way to override paste event. I'm not sure, that it is a right way, but it works.
In every TextField you have selectionControls, that provides a way to show and handle toolbar controls.
So, to catch paste event first:
create your own version of selection controls, for example
class AppCupertinoTextSelectionControls extends CupertinoTextSelectionControls {
AppCupertinoTextSelectionControls({
required this.onPaste,
});
ValueChanged<TextSelectionDelegate> onPaste;
#override
Future<void> handlePaste(final TextSelectionDelegate delegate) {
onPaste(delegate);
return super.handlePaste(delegate);
}
}
class AppMaterialTextSelectionControls extends MaterialTextSelectionControls {
AppMaterialTextSelectionControls({
required this.onPaste,
});
ValueChanged<TextSelectionDelegate> onPaste;
#override
Future<void> handlePaste(final TextSelectionDelegate delegate) {
onPaste(delegate);
return super.handlePaste(delegate);
}
}
then, initialise it in your state (for example in StatefulWidget it can looks like that, see below). To study how it used in TextField please see source here
TextSelectionControls? _selectionControls;
#override
void initState() {
if (widget.onPaste != null) {
if (Platform.isIOS) {
_selectionControls = AppCupertinoTextSelectionControls(
onPaste: widget.onPaste!,
);
} else {
_selectionControls = AppMaterialTextSelectionControls(
onPaste: widget.onPaste!,
);
}
}
super.initState();
}
Use callback for onPaste with a type ValueChanged<TextSelectionDelegate> and you can use the same code the Flutter team used to get Clipboard data:
Future<void> onPastePhone(final TextSelectionDelegate? delegate) async {
final TextSelection selection = phoneController.selection;
if (!selection.isValid) {
return;
}
// Snapshot the input before using `await`.
// See https://github.com/flutter/flutter/issues/11427
final ClipboardData? data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text ?? '';
if (text.isEmpty) {
return;
}
}
Then use selection controls in your TextField.
TextFormField(
selectionControls: _selectionControls,
)
Hope it helps.
I search for this problem. I think there is no proper way to solve this problem. I read about the Textfield class and found two solutions for it.
if you check TextField widget you can find that it will use EditableText to show its simple Text input. EditableText has a selectionControls property. this property is used to render the selection toolbar. also, I found that material and Cupertino have different implementation of it.
1st Solution: you can create your own custom TextField that will use EditableText and pass your custom selectionControl to your widget. I think this gonna be a very hard job to do. create your own implementation of the widget, handling animations, and...
2nd Solution: You can simply copy all related files of TextField in a new file and update it as you want. for this solution, I create a repo in GitHub. you can checkout source code to understand how you can show a dialog in the paste option. and this is how the code should work.
note: I just simply update paste function of the Material implementation of selectionControls. if you want you can also update the Cupertino selectionControls too.
note: also I added documents in everywhere I change the code.

How can I run a future before build in flutter?

I am not able to run getMapCurrencies before the build, and I need values in listCurrencies before the view. I can not put the future builder in the build because I dont want to bring listCurrencies many times, just once.
Please help
getMapCurrencies() {
currencies.getCurrenciesCheck().then((val) {
listCurrencies = val;
});
}
class _CurrencyWidgetState extends State<CurrencyWidget> {
#override
void initState() {
// TODO: implement initState
getMapCurrencies();
super.initState();
}
What do you mean by "I dont want to bring listCurrencies many times, just once"
FutureBuilder is one way you can do this. It will render the widget once listCurrencies is populated.
Another way is to use a ternary operator
listCurrencies != null ? (widget using listcurrencies) : (a progress indicator)
Edit:
Also you should set listCurrencies using
setState((){
listCurrencies = val;
})