Variable value gets null outside setState() in Flutter - flutter

TextField(
style: TextStyle(
fontFamily: "Averta",
fontWeight: FontWeight.bold,
fontSize: 16,
color: Colors.black),
enableSuggestions: true,
onChanged: (value) {
setState(() {
final title = value;
print(title);
});
},
decoration: InputDecoration(
border: InputBorder.none,
contentPadding:
EdgeInsets.all(18),
hintText: "Enter Task Title",
hintStyle: TextStyle(
fontFamily: "Averta",
fontWeight: FontWeight.normal,
fontSize: 12,
color: Colors.grey.shade300),
),
),
Here,I have a title variable which I update with onChanged() function.
Here the print() function shows exact change in value which I do in TextField.
But I don't want to pass it here, I want to take some more data and then pass it when I click the CREATE button here-
InkWell(
onTap: () {
print(title);
setState(() {
DatabaseHelper _dbhelper =
DatabaseHelper();
Task _newTask = Task(
title: title,
year: year,
month: month,
day: daye,
hour: hour,
minute: minute,
weekday: weekday);
_dbhelper
.insertTask(_newTask);
});
}
Here the print statement shows "null",but I want to use the value which was updated above in TextField.
How can I achieve this in Flutter?

This line creates a new variable called title and sets it:
final title = value;
You want to access the already existing variable:
title = value;
That should work.

Related

Dynamically load list of words from API as map in highlight_text: ^1.6.0

I need to highlight some words in a text. I used highlight_text 1.6.0.
Map<String, HighlightedWord> words = {
"Flutter": HighlightedWord(
textStyle: textStyle,
),
"words": HighlightedWord(
textStyle: textStyle,
),
};
TextHighlight(
text: text,
words: words,
matchCase: false,
textStyle: TextStyle(
fontSize: 14.0,
color: Colors.black,
),
textAlign: TextAlign.justify,
)
It is working fine when given static values.
Is it possible to load the highlighted words from API like a list instead of the map?
List=["Flutter", "Words"]
Lets assume you get this sample list from api:
List sample = ["Flutter", "Words"];
then you can use fromIterable:
var result = Map<String, HighlightedWord>.fromIterable(sample,
key: (v) => v,
value: (v) => HighlightedWord(
textStyle: textStyle,
),
);
then use result in TextHighlight:
TextHighlight(
text: text,
words: result,
matchCase: false,
textStyle: TextStyle(
fontSize: 14.0,
color: Colors.black,
),
textAlign: TextAlign.justify,
)

When tap on textfield, app crashes returns homepage

Hi I get an error when user focus textfield, app crashes and returns to homepage (see clip here https://www.screencast.com/t/yiJkCBsibcoY)
I've had this error for a while now and cannot seem to fix it, sometimes it happens on other textfields. I cannot replicate the issue only sent from users. Anyone experience this with flutter?
Widget searchBox() {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
border: Border.all(color: Color(0xff0F004E), width: 1.0),
),
child: SimpleAutoCompleteTextField(
key: keyAuto,
controller: textController,
suggestions: suggestions,
textChanged: (text) => searchProduct = text,
textSubmitted: (text) {
loadingBarActive = true;
_sendAnalyticsEvent(text, 'serach_food_action');
searchProduct = text.replaceAll(new RegExp(r'[^\w\s]+'), '');
print('searchProduct RegX $searchProduct');
newSearch = true;
_filterCategories(searchProduct);
_filterRecipes(searchProduct);
// reset search values to intial
usdaItems.clear();
usda!.clear();
perPage = perPageIntial;
present.value = 0;
loadingBarActive = false;
selectApi = <int, Widget>{
0: allProductTab(),
1: allProductTab(),
2: allProductTab(),
3: allProductTab(),
};
setState(() {
_loadUSDAlist = usdaFoodProductList();
_loadOpenList = openFoodProductList();
});
},
style: TextStyle(
fontFamily: 'Nunito', fontSize: 20.0, color: Color(0xff0F004E)),
decoration: InputDecoration(
border: InputBorder.none,
// contentPadding: EdgeInsets.only(top: 14.0),
hintText: 'Search',
hintStyle: TextStyle(
fontFamily: 'Nunito', fontSize: 16.0, color: Color(0xff0F004E)),
prefixIcon: Icon(Icons.search, color: Color(0xff0F004E)),
suffixIcon: IconButton(
icon: Icon(Icons.close, color: Color(0xff0F004E)),
onPressed: () {
textController.clear();
})),
),
);
}
I had exactly the same issue and was literally going crazy trying to find the solution. For me the error originated in my usage of the GetX state management library. For me the issue was solved by replacing this:
Get.to(ReservationDetails(res: Reservation.empty()))
?.then(((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
})));
with:
Navigator.push(context,
MaterialPageRoute(
builder: ((context) =>
ReservationDetails(res: Reservation.empty()))))
.then((value) => setState(() {
//Reload the reservations for the new date from the server
_taskesFuture =
FetchReservation(setStatePublic: _setStatePublic)
.fetchReservation(_selectedDate);
}));
I suggest you have a look at how you are opening the page you are experiencing this issue.

Flutter TextFormField controller into Text

i have a problem :( I have a Detailform with Text Widget wehre im getting values from my DB.
I have one TextFormField with a controller, because i need to set the actual price, after i submitted it, the new value will updated in a TextValueField, but i want it to show on a normal Text widget.
i hope you can understand my problem. but here my code
TextField(
decoration: InputDecoration(labelText: 'actual cost'),
controller: _profitController,
keyboardType:
TextInputType.numberWithOptions(decimal: true),
onSubmitted: (val) {
double amount =
double.parse(selectedEntry.amount); // 1 value
double aktPrice =
double.parse(val); // 2 value from this textfield
double profit = aktPrice * amount; // calc
_endProfitController.text = profit.toString();
newProfit = profit;
},
),
TextFormField(
readOnly: true,
decoration: InputDecoration(labelText: "profit"),
controller:
_endProfitController, //this is getting updated with the controller
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 20,
color: Colors.grey[700],
),
),
Text(
'test profit: ' +
_endProfitController.text.toString() + newProfit.toString() +
' €', // this is not getting updated, and newProfit says "Null"...
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 20,
color: Colors.grey[700],
),
),
alright, how can i get the value in my Text Widget ?
I tried to setState in the onSubmitted but then the controller also isn't updating.
I tried to declare a new double newProfit but after submit it still gives me null back....
hope someone can help me :)
best regards
And thanks for your time :)
Its not updating because the widgets are already built when you change the text value of the controller if you are creating the form inside a stateful widget you can call setState() inside the onChanged so the value of the field updates the String you'll use to show the text, something like this.
TextFormField(
decoration: InputDecoration(labelText: "profit"),
controller:
_endProfitController, //this is getting updated with the controller
textAlign: TextAlign.left,
onChanged: (value) {
setState(() {
valueText = _endProfitController.text;
});
print(valueText);
},
style: TextStyle(
fontSize: 20,
color: Colors.grey[700],
),
),
Text(
'test profit: ' +
valueText +
' €', // this is not getting updated, and newProfit says "Null"...
style: TextStyle(
fontSize: 20,
color: Colors.grey[700],
),
),
The variable that will get the value of the controller's text has to be outside the build method
String valueText = '';
If you are not building this inside a stateful widget you can look at the Provider package to update a value that has no state

Backspace doesn't work correctly with TextInputFormatter

I'm trying to a create custom InputTextFormatter.
The formatter separates thousands with spaces and limits amount of characters after a dot to 2 chars.
I want to move the cursor to the end of the TextField value, but it looks like the real cursor moves further according to how many times I've tried to enter additional characters after reaching the limit (2 chars).
It looks like selection not applies to resulting TextEditingValue.
Steps to reproduce:
Enter a '12.34' to TextField.
Keeping previous value try to add
'111' for example.
Press backspace. Nothing happens.
Expected behavior: pressing backspace once must delete the last character in the TextField.
class MoneyFormatter extends TextInputFormatter {
MoneyFormatter({this.maxLength = 30, this.decimals = 0});
final int maxLength;
final int decimals;
#override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
print('---------- newValue.selection.extentOffset : ${newValue.selection.extentOffset}');
String output = newValue.text.formatAsCurrency(decimals: decimals);
var result = TextEditingValue(
text: output,
//this line doesn't have any effect
selection: TextSelection.collapsed(offset: output.length),
);
print('---------- result.selection.extentOffset : ${result.selection.extentOffset}');
return result;
}
}
With every additional character result.selection.extentOffset stays the same but newValue.selection.extentOffset increases by 1 despite the fact returning selection: TextSelection.collapsed(offset: output.length)
extension FormatAsCurrency on String {
String formatAsCurrency({int decimals = 0, String ifNullReturn}) {
if (this == null) return ifNullReturn;
if (this.isEmpty) return '';
String output = this;
if (output[0] == '.') output = '0' + output;
var chunks = this.withoutTrailingDots.split('.');
output = chunks[0].separatedThousands;
if (decimals == 0 || chunks.length == 1) return output;
output += '.' + chunks[1].limitLengthTo(decimals).withoutTrailingZeros;
return output;
}
}
I'm aware there are other TextInputFormatters on pub.dev like flutter_multi_formatter, I've tried all of them, the problem stays the same.
Use \b in your regex :
TextField(
controller: tvMobile,
keyboardType: TextInputType.number,
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.allow(
RegExp(r'[0-9,\b]')), // <-- Use \b in your regex here so backspace works.
],
maxLength: 10,
style: TextStyle(
color: Colors.white,
fontFamily: "Roboto",
fontWeight: FontWeight.w300,
),
decoration: InputDecoration(
labelStyle: TextStyle(
color: Colors.white,
fontFamily: "Roboto",
fontWeight: FontWeight.w300,
),
fillColor: Colors.white,
enabledBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: Colors.yellow),
),
focusedBorder: UnderlineInputBorder(
borderSide:
BorderSide(color: Colors.yellow),
),
hintText: 'Mobile Number',
hintStyle: TextStyle(
color: Colors.grey,
fontFamily: "Roboto",
fontWeight: FontWeight.w300,
),
),
),
I found the backspacing problem when I try to use formatter with keyboard types number. The cursor tends to skip character(s) for each backspacing. It works fine if I use keyboard type text.

How can I save radiobutton group data in list?

I am making one quiz app. I have 10 questions list and each have four option. User select answer one by one. Then all answers save and give result in last screen.
//This is a code of radiobuttongroup
child: RadioButtonGroup(
padding: EdgeInsets.all(20.0),
labels: <String>[
que_list[index]['option_list'][0],
que_list[index]['option_list'][1],
que_list[index]['option_list'][2],
que_list[index]['option_list'][3]
],
labelStyle: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.white),
onChange: (String label, int index) {},
onSelected: (String selected) async {
setState(() {
_picked = selected;
});
//print(selected);
print(">>>>>>>>>" + _picked);
},
picked: _picked,
activeColor: Colors.white,
},
),
I am getting data from API.
Make another list of answers entered like this -
List<String> selectedAns = [];
After selecting, keep adding the answers to this list-
selectedAns.add(selected);