Conditional statement within SetState is not updating widget - flutter

I have a Column with some widgets. Inside the Column are some TextFields. When the textfields receive and lose focus I want to hide a widget. I think when calling SetState it is not redrawing the conditional below.
AutoCompleteTextField:
child: AutoCompleteTextView(
suggestionsApiFetchDelay: 300,
focusGained: () {
_pauseStream(
stream: Streams.dropoff);
_startStream(
stream: Streams.pickup);
setState(() {
_showCurrentLocalTile = true;
});
},
focusLost: () {
setState(() {
_showCurrentLocalTile = false;
});
_pauseStream(
stream: Streams.dropoff);
}
)
void _showBottomSheet() {
setState(() {
_showPersBottomSheetCallBack = null;
});
// Be sure to set to get and set current physical address
LocationService().getAddressFromLatLng().then((value) {
if (value != null) {
_currentAddress = value;
}
});
_scaffoldKey.currentState
.showBottomSheet((context) {
return new Container(
height: 400.0,
color: Colors.white,
padding: const EdgeInsets.only(left: 2, right: 2),
child: new Center(
// child: new Text('Persistent Bottom Sheet'),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
height: 125,
child: Row(
children: [
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: [
IconButton(
icon: Icon(Icons.arrow_back),
color: Colors.black,
onPressed: () {},
),
],
),
Expanded(
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Container(
alignment: Alignment.topCenter,
height: 35,
margin: const EdgeInsets.only(
top: 40, left: 0, right: 0),
child: AutoCompleteTextView(
suggestionsApiFetchDelay: 300,
focusGained: () {
_pauseStream(
stream: Streams.dropoff);
_startStream(
stream: Streams.pickup);
setState(() {
_showCurrentLocalTile = true;
});
},
onTapCallback: (_) async {
_startStream(
stream: Streams.dropoff);
// locationSavedStatus = LocationSaveStatus.inProgress;
// saveLocationValuesFromGeoCoding(bloc).then(
// (_) =>
// locationSavedStatus = LocationSaveStatus.saved,
// );
},
focusLost: () {
setState(() {
_showCurrentLocalTile = false;
});
_pauseStream(
stream: Streams.dropoff);
// locationSavedStatus = LocationSaveStatus.saved;
// if (startEditingController.text.isEmpty) {
// city = '';
// state = '';
// country = '';
// startEditingController.text = '';
// } else {
// startEditingController.text = getLocationString(
// country: country, state: state, city: city);
// }
},
onValueChanged: (String text) {
// locationSavedStatus = text.isNotEmpty
// ? (getLocationString(
// city: '', state: '', country: '')
// .trim() ==
// text.trim())
// ? LocationSaveStatus.saved
// : LocationSaveStatus.notSaved
// : LocationSaveStatus.saved;
},
controller: startEditingController,
suggestionStyle: Theme.of(context)
.textTheme
.bodyText2,
getSuggestionsMethod:
getLocationSuggestionsList,
tfTextAlign: TextAlign.left,
tfCursorColor: Colors.black,
tfStyle: TextStyle(
fontSize: 16,
color: Theme.of(context)
.textTheme
.bodyText2
.color,
),
tfTextDecoration: InputDecoration(
contentPadding: EdgeInsets.only(
top: 0, left: 8.0),
filled: true,
fillColor: Colors.grey[200],
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
width: 1.0),
borderRadius: BorderRadius.zero,
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
width: 1.0),
borderRadius: BorderRadius.zero,
),
hintText: "",
labelText: 'Start',
labelStyle:
kPurpleLabelStyle,
),
),
),
Container(
height: 35,
margin: const EdgeInsets.only(
top: 5,
left: 0,
right: 0,
bottom: 5),
child: AutoCompleteTextView(
suggestionsApiFetchDelay: 300,
focusGained: () {
setState(() {
_showCurrentLocalTile = true;
});
_pauseStream(
stream: Streams.pickup);
_startStream(
stream: Streams.dropoff);
},
onTapCallback: (_) async {
_startStream(
stream: Streams.pickup);
// locationSavedStatus = LocationSaveStatus.inProgress;
// saveLocationValuesFromGeoCoding(bloc).then(
// (_) =>
// locationSavedStatus = LocationSaveStatus.saved,
// );
},
focusLost: () {
setState(() {
_showCurrentLocalTile = false;
});
_pauseStream(
stream: Streams.pickup);
// locationSavedStatus = LocationSaveStatus.saved;
// if (startEditingController.text.isEmpty) {
// city = '';
// state = '';
// country = '';
// startEditingController.text = '';
// } else {
// startEditingController.text = getLocationString(
// country: country, state: state, city: city);
// }
},
onValueChanged: (String text) {
// locationSavedStatus = text.isNotEmpty
// ? (getLocationString(
// city: '', state: '', country: '')
// .trim() ==
// text.trim())
// ? LocationSaveStatus.saved
// : LocationSaveStatus.notSaved
// : LocationSaveStatus.saved;
},
controller:
destinationEditingController,
suggestionStyle: Theme.of(context)
.textTheme
.bodyText2,
getSuggestionsMethod:
getLocationSuggestionsList,
tfTextAlign: TextAlign.left,
tfCursorColor: Colors.black,
tfStyle: TextStyle(
fontSize: 16,
color: Theme.of(context)
.textTheme
.bodyText2
.color,
),
tfTextDecoration: InputDecoration(
contentPadding: EdgeInsets.only(
top: 0, left: 8.0),
filled: true,
fillColor: Colors.grey[300],
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
width: 1.0),
borderRadius: BorderRadius.zero,
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.white,
width: 1.0),
borderRadius: BorderRadius.zero,
),
hintText: "",
labelText: 'Destination',
labelStyle:
kPurpleLabelStyle,
),
),
)
]),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Stack(
alignment: Alignment.bottomLeft,
children: [
ButtonTheme(
padding: EdgeInsets.symmetric(
vertical: 4.0,
horizontal:
8.0), //adds padding inside the button
materialTapTargetSize:
MaterialTapTargetSize
.shrinkWrap, //limits the touch area to the button area
minWidth: 45, //wraps child's width
height: 45, //wraps child's height
child: FlatButton(
color: Colors.white,
textColor: Colors.black,
disabledColor: Colors.grey[100],
disabledTextColor: Colors.white,
padding: EdgeInsets.only(
top: 10,
left: 8,
bottom: 8,
right: 12),
splashColor: Colors.grey[100],
onPressed: () {
/*...*/
},
child: Text(
"Done",
style:
TextStyle(fontSize: 14.0),
),
),
),
// IconButton(
// icon: Icon(Icons.add),
// color: Colors.black,
// onPressed: () {},
// ),
]),
],
),
]),
),
],
),
),
SizedBox(
height: 15.0,
),
_showCurrentLocalTile
? GestureDetector(
onTap: () {
_setPickupAddressToAutoComplete(_currentAddress);
print(_currentAddress);
},
child: Container(
height: 48,
child: Padding(
padding: const EdgeInsets.fromLTRB(
16.0, 8.0, 16.0, 0.0),
child: Row(
children: <Widget>[
Icon(Icons.my_location),
Padding(
padding: EdgeInsets.only(
left: 8.0, top: 0.0, bottom: 0.0),
child: Text("Current Location"),
)
],
),
),
),
)
: SizedBox(
height: 15.0,
),
Container(
height: 200,
child: Padding(
padding: const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 8.0),
child: StreamBuilder<List<GoogleAddress>>(
stream: pickupStreamController.stream,
builder: (context, snapshot) => snapshot.data != null
? ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
print('Render $index');
if (snapshot.data != null) {
print("${snapshot.data}");
return _createListItem(
icon: Icons.location_on,
googleplace: snapshot.data[index],
onTap: () {
_setPickupAddressToAutoComplete(
snapshot.data[index].address);
print("${snapshot.data[index]}");
});
} else {}
},
)
: SizedBox(height: 15.0),
),
),
),
],
),
),
);
})
.closed
.whenComplete(() {
if (mounted) {
setState(() {
_showPersBottomSheetCallBack = _showBottomSheet;
});
}
});
}

Related

How to access context and setstate outside build method in Flutter

How to access context and setstate outside build method in Flutter?
To make the app responsive I need context.
I get error "Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name."
When I write context here:-
class Portfolio extends StatefulWidget {
final BuildContext context1;
const Portfolio({
required this.context1,
Key? key,
}) : super(key: key);
#override
State<Portfolio> createState() => _PortfolioState();
}
DragAndDropList buildList(CardsList list) => DragAndDropList(
header: Padding(
padding: EdgeInsets.only(
left: 15.0,
top: 10,
bottom: 10,
right: 15,
),
child: Row(
children: [
Text(
list.header,
style: TextStyle(
color: Color(0xFF100F32),
fontWeight: FontWeight.w700,
fontSize: responsiveWidth(14, context),
),
),
Spacer(),
Icon(
Icons.more_horiz,
color: Color(0xFF364766),
size: 20,
),
],
),
),
children: list.cards
.map(
(item) => DragAndDropItem(
child: Center(
child: Padding(
padding: EdgeInsets.only(top: 8.0),
child: Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.all(10),
child: Text(item.text),
),
),
),
),
)
.toList(),
footer: Padding(
padding: EdgeInsets.only(left: 10.0, bottom: 10),
child: addCard == false
? OPopupTrigger(
triggerWidget: Row(
children: [
Icon(
Icons.add,
color: Color(0xFF80899D),
),
Text(
'Add a card',
style: TextStyle(
color: Color(0xFF80899D),
fontSize: 12,
),
),
],
),
barrierDismissible: true,
popupHeader: SizedBox(),
popupContent: Container(
height: 100,
width: 100,
color: Colors.red,
child: Row(
children: [
Text('Hehehe'),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(Icons.cancel),
),
],
),
),
)
: Column(
children: [
Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.only(left: 10, top: 10, bottom: 25),
child: TextField(
onChanged: (newText) {
list.textField = newText;
},
maxLines: null,
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
hintText: 'Enter a title for this card...',
hintStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
labelStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
),
),
style: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
),
),
SizedBox(
height: 20,
),
Row(
children: [
GestureDetector(
onTap: () {
list.cards.add(
Cards(text: list.textField, position: 1),
);
print(list.textField);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xFF026AA7),
borderRadius: BorderRadius.circular(5),
),
height: 30,
width: 80,
child: Center(
child: Text(
'Add card',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
),
),
GestureDetector(
onTap: () {
addCard = false;
},
child: Icon(
Icons.close,
color: Color(0xFF80899D),
size: 24,
),
),
],
),
],
),
),
);
class _PortfolioState extends State<Portfolio> {
#override
void initState() {
// TODO: implement initState
lists = widgets.map(buildList).toList();
}
late List<DragAndDropList> lists;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
Full code file:-
import 'package:expandable_reorderable_list/expandable_reorderable_list.dart';
import 'package:flutter/material.dart';
import 'package:o_popup/o_popup.dart';
import 'package:project_submission/responsive.dart';
import 'drag_and_drop_list.dart';
void main() {
runApp(const MyApp());
}
class CardsList {
final String header;
final List<Cards> cards;
String textField;
CardsList({
required this.header,
required this.cards,
this.textField = '',
});
}
class Cards {
final String text;
final int position;
const Cards({
required this.text,
required this.position,
});
}
List<CardsList> widgets = [
CardsList(
header: 'To-do',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header2',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header3',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header4',
textField: '',
cards: [
Cards(text: 'Hello1', position: 1),
Cards(text: 'Hello2', position: 2),
Cards(text: 'Hello3', position: 3),
],
),
];
bool addCard = false;
bool greyArea = false;
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: Wait());
}
}
class Wait extends StatefulWidget {
const Wait({Key? key}) : super(key: key);
#override
State<Wait> createState() => _WaitState();
}
class _WaitState extends State<Wait> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Portfolio(
context1: context,
)));
},
child: Text('Wait'),
);
}
}
class Portfolio extends StatefulWidget {
final BuildContext context1;
const Portfolio({
required this.context1,
Key? key,
}) : super(key: key);
#override
State<Portfolio> createState() => _PortfolioState();
}
DragAndDropList buildList(CardsList list) => DragAndDropList(
header: Padding(
padding: EdgeInsets.only(
left: 15.0,
top: 10,
bottom: 10,
right: 15,
),
child: Row(
children: [
Text(
list.header,
style: TextStyle(
color: Color(0xFF100F32),
fontWeight: FontWeight.w700,
fontSize: responsiveWidth(14, context),
),
),
Spacer(),
Icon(
Icons.more_horiz,
color: Color(0xFF364766),
size: 20,
),
],
),
),
children: list.cards
.map(
(item) => DragAndDropItem(
child: Center(
child: Padding(
padding: EdgeInsets.only(top: 8.0),
child: Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.all(10),
child: Text(item.text),
),
),
),
),
)
.toList(),
footer: Padding(
padding: EdgeInsets.only(left: 10.0, bottom: 10),
child: addCard == false
? OPopupTrigger(
triggerWidget: Row(
children: [
Icon(
Icons.add,
color: Color(0xFF80899D),
),
Text(
'Add a card',
style: TextStyle(
color: Color(0xFF80899D),
fontSize: 12,
),
),
],
),
barrierDismissible: true,
popupHeader: SizedBox(),
popupContent: Container(
height: 100,
width: 100,
color: Colors.red,
child: Row(
children: [
Text('Hehehe'),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(Icons.cancel),
),
],
),
),
)
: Column(
children: [
Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.only(left: 10, top: 10, bottom: 25),
child: TextField(
onChanged: (newText) {
list.textField = newText;
},
maxLines: null,
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
hintText: 'Enter a title for this card...',
hintStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
labelStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
),
),
style: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
),
),
SizedBox(
height: 20,
),
Row(
children: [
GestureDetector(
onTap: () {
list.cards.add(
Cards(text: list.textField, position: 1),
);
print(list.textField);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xFF026AA7),
borderRadius: BorderRadius.circular(5),
),
height: 30,
width: 80,
child: Center(
child: Text(
'Add card',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
),
),
GestureDetector(
onTap: () {
addCard = false;
},
child: Icon(
Icons.close,
color: Color(0xFF80899D),
size: 24,
),
),
],
),
],
),
),
);
class _PortfolioState extends State<Portfolio> {
#override
void initState() {
// TODO: implement initState
lists = widgets.map(buildList).toList();
}
late List<DragAndDropList> lists;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
children: [
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFF2B1B81),
Color(0xFFDD499D),
],
),
),
),
Text(
'Project Management',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 20,
),
),
Padding(
padding: EdgeInsets.only(
left: 10,
top: 30,
),
child: DragAndDropLists(
listWidth: 300,
axis: Axis.horizontal,
listPadding: EdgeInsets.only(right: 10),
itemDragOnLongPress: false,
children: lists,
onItemReorder: onItemReorder,
onListReorder: onListReorder,
),
),
// Row(
// children: [
// DragTarget(
// onAccept: (data) {
// setState(() {
// widgets.add(data);
// widgets.remove(data);
// });
// },
// onWillAccept: (data) {
// setState(() {
// greyArea = true;
// });
// return true;
// },
// onLeave: (data) {
// setState(() {
// greyArea = false;
// widgets
// .sort((a, b) => a['position'].compareTo(b['price']));
// });
// },
// builder: (context, _, __) => SizedBox(
// height: MediaQuery.of(context).size.height,
// child: Column(
// children: [
// Padding(
// padding: EdgeInsets.only(left: 30.0, top: 30),
// child: Container(
// width: 300,
// decoration: BoxDecoration(
// color: Color(0xFFEBECF0),
// borderRadius: BorderRadius.circular(6),
// ),
// child: Column(
// children: [
// Text(
// 'Project Resources',
// style: TextStyle(
// color: Color(0xFF5D6C83),
// fontWeight: FontWeight.w600,
// fontSize: 12),
// ),
// for (var wid in widgets)
// Column(
// children: [
// Padding(
// padding: EdgeInsets.all(8.0),
// child: Draggable(
// child: Container(
// decoration: BoxDecoration(
// color: Colors.green,
// ),
// child: Text(wid['text']),
// height: 100,
// width: 100,
// ),
// data: wid,
// feedback: Container(
// color: Colors.red,
// height: 100,
// width: 100,
// ),
// childWhenDragging: SizedBox(),
// ),
// ),
// DragTarget(
// onAccept: (data) {
// setState(() {
// widgets.add({
// 'text': data['text'],
// 'position': 1
// });
// widgets.remove({
// 'text': data['text'],
// 'position': data['position']
// });
// });
// },
// onWillAccept: (data) {
// setState(() {
// greyArea = true;
// });
// return true;
// },
// onLeave: (data) {
// setState(() {
// greyArea = false;
// });
// },
// builder: (context, _, __) {
// print(_);
// return SizedBox();
// },
// ),
// ],
// ),
// greyArea == true
// ? Container(
// color: Colors.grey,
// height: 20,
// width: 100,
// )
// : SizedBox(),
// SizedBox(
// height: 8,
// ),
// ],
// ),
// ),
// ),
// ],
// ),
// ),
// ),
// ],
// ),
],
),
),
);
}
void onItemReorder(
int oldItemIndex,
int oldListIndex,
int newItemIndex,
int newListIndex,
) {
setState(() {
final oldListItems = lists[oldListIndex].children;
final newListItems = lists[newListIndex].children;
final movedItem = oldListItems.removeAt(oldItemIndex);
newListItems.insert(newItemIndex, movedItem);
});
print(lists);
}
void onListReorder(
int oldListIndex,
int newListIndex,
) {
setState(() {
final movedList = lists.removeAt(oldListIndex);
lists.insert(newListIndex, movedList);
});
}
}

How to remove middle numbers in PinFieldAutoFill flutter?

When I entering an OTP it continuously adding numbers from the beginning but how do I change the middle number from entered 6 digit OTP
I have used this in Model Bottom Sheet
Column(
children: [
SizedBox(
height: 50,
child: PinFieldAutoFill(
textInputAction: TextInputAction.previous,
keyboardType: TextInputType.number,
autoFocus: true,
focusNode: FocusNode(),
cursor: Cursor(
width: 2,
height: 40,
color: Colors.red,
radius: const Radius.circular(5),
enabled: true,
),
decoration: UnderlineDecoration(
textStyle: const TextStyle(
fontSize: 20, color: Colors.black),
colorBuilder: FixedColorBuilder(
Colors.black.withOpacity(0.3)),
),
currentCode: code,
codeLength: 6,
onCodeSubmitted: (verificationCode) {
debugPrint("CURRENT CODE CHANGES 2: " +
verificationCode.toString());
otpNumber = verificationCode;
},
onCodeChanged: (verificationCode) {
debugPrint("CURRENT CODE CHANGES 3: " +
verificationCode.toString());
if (verificationCode.toString().length == 6) {
// FocusScope.of(context)
// .requestFocus(FocusNode());
setState(() {
code = verificationCode.toString();
otpNumber = verificationCode.toString();
});
}
},
),
// child: OtpTextField(
// onSubmit: (String verificationCode) {
// setState(() {
// otpNumber = verificationCode;
// debugPrint(otpNumber);
// });
// },
// cursorColor: primaryDarkColor,
// numberOfFields: 6,
// borderColor: primaryDarkColor,
// focusedBorderColor: primaryColor,
// enabledBorderColor: primaryDarkColor,
// fillColor: hintColor,
// borderWidth: 2.0,
// fieldWidth: 40,
// mainAxisAlignment:
// MainAxisAlignment.spaceEvenly,
// filled: true,
// showFieldAsBox: true,
// textStyle: kkTitleTextStyle,
// ),
),
const SizedBox(height: 20),
SizedBox(
height: 45,
width: MediaQuery.of(context).size.width * 0.43,
child: ElevatedButton(
onPressed: () {
verify();
},
child: const Text('Submit OTP'),
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 20.0),
primary: primaryDarkColor,
textStyle: kkTitleTextStyle,
),
),
),
const SizedBox(height: 20),
isResend
? const Center(
child: Text(
'Didn't receive any OTP ?',
style: kkMediumGrayTextStyle,
),
)
: const Center(
child: Text(
'',
style: kkMediumGrayTextStyle,
),
),
const SizedBox(height: 5),
isResend
? GestureDetector(
onTap: () {
setModalState(() {
if (_controller.isCompleted) {
fetchOtp(phoneNumberController.text
.toString());
_controller = AnimationController(
duration:
const Duration(seconds: 30),
vsync: this);
_controller.forward();
isResend = false;
} else {
debugPrint('TIME IS RUNNING');
}
debugPrint(
'VALUE: ${_controller.value}');
debugPrint(
'STATUS: ${_controller.status}');
debugPrint(
'IS_ANIMATING: ${_controller.isAnimating}');
debugPrint(
'IS_COMPLETED: ${_controller.isCompleted}');
});
},
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
const Text(
'Resend OTP',
style: kkTitleTextStyle,
),
const SizedBox(width: 10.0),
CountDown(
animation: StepTween(
begin: 30,
end: 0,
).animate(_controller),
),
],
),
)
: GestureDetector(
onTap: () {
// setState(() {
// if (_controller.isCompleted) {
// fetchOtp(
// phoneNumberController.text.toString());
// _controller = AnimationController(
// duration: const Duration(seconds: 30),
// vsync: this);
// _controller.forward();
// } else {
// debugPrint('TIME IS RUNNING');
// }
//
// });
debugPrint('VALUE: ${_controller.value}');
debugPrint(
'STATUS: ${_controller.status}');
debugPrint(
'IS_ANIMATING: ${_controller.isAnimating}');
debugPrint(
'IS_COMPLETED: ${_controller.isCompleted}');
},
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
const Text(
'Seconds Remaining',
style: kkTitleTextStyle,
),
const SizedBox(width: 10.0),
CountDown(
animation: StepTween(
begin: 30,
end: 0,
).animate(_controller),
),
],
),
),
],
)

only when use iphone simulator

I have this error:
The following FileSystemException was thrown resolving an image codec:
Cannot open file, path = '/Users/todo/Library/Developer/CoreSimulator/Devices/82205CEC-3D83-4A29-BF17-01C5B0515F71/data/Containers/Data/Application/035B9913-BEC5-46BA-84A5-8C1FE3C4E671/tmp/image_picker_B8D488A3-2790-4D53-A5D8-52E57E2C4108-76094-000003172DF085D2.jpg' (OS Error: No such file or directory, errno = 2)
When the exception was thrown, this was the stack
only when use iphone simulator while android emulator no problem
import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../app/utility.dart';
import '../db/aql_db.dart';
import '../globals.dart';
import '../menu_page.dart';
import '../model/aql_model.dart';
import '../widget/input_text.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
var _current = resultsFld[0];
class AqlPg extends StatefulWidget {
const AqlPg({Key? key}) : super(key: key);
#override
State<AqlPg> createState() => _AqlPgState();
}
class _AqlPgState extends State<AqlPg> {
final List<TextEditingController> _criticalController = [];
final List<TextEditingController> _majorController = [];
final List<TextEditingController> _minorController = [];
final List<TextEditingController> _imgCommintControllers = [];
final _irController = TextEditingController();
bool clickedCentreFAB =
false; //boolean used to handle container animation which expands from the FAB
int selectedIndex =
0; //to handle which item is currently selected in the bottom app bar
//call this method on click of each bottom app bar item to update the screen
void updateTabSelection(int index, String buttonText) {
setState(() {
selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
//
_irController.text = aqltbl.ir ?? '';
String _current = aqltbl.result ?? resultsFld[0];
//
return Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
children: [
//---- stack for FloatingActionButton
Stack(
children: <Widget>[
//this is the code for the widget container that comes from behind the floating action button (FAB)
Align(
alignment: FractionalOffset.bottomCenter,
child: AnimatedContainer(
child: const Text(
'Hello',
style: TextStyle(fontSize: 18, color: whiteColor),
),
duration: const Duration(milliseconds: 250),
//if clickedCentreFAB == true, the first parameter is used. If it's false, the second.
height: clickedCentreFAB
? MediaQuery.of(context).size.height
: 10.0,
width: clickedCentreFAB
? MediaQuery.of(context).size.height
: 10.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(
clickedCentreFAB ? 0.0 : 300.0),
color: Colors.blue),
),
),
],
),
// --- Top Page Title
const SizedBox(
height: 50,
),
const Center(
child: Text(
'Aql page',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: medBlueColor),
),
),
Text(
'Shipment no:$shipmentId',
style: const TextStyle(color: medBlueColor),
),
//--- input container
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Container(
height: 270,
width: 300,
margin: const EdgeInsets.only(top: 5),
child: ListView.builder(
itemCount: (aqltbl.aql ?? []).length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
//here
var _aqlList = aqltbl.aql![index];
//
if (aqltbl.aql!.length > _criticalController.length) {
_criticalController.add(TextEditingController());
_majorController.add(TextEditingController());
_minorController.add(TextEditingController());
}
//
_criticalController[index].text =
_aqlList.critical ?? '';
_majorController[index].text = _aqlList.major ?? '';
_minorController[index].text = _aqlList.minor ?? '';
//
return Column(
children: [
Container(
height: 260,
width: 200,
margin: const EdgeInsets.only(left: 10),
padding: const EdgeInsets.all(10),
// ignore: prefer_const_constructors
decoration: BoxDecoration(
color: lightBlue,
borderRadius: BorderRadius.circular(10),
),
child: Column(
children: [
Text(
(_aqlList.name ?? '').toString(),
style: const TextStyle(
color: medBlueColor,
fontSize: 13,
),
),
// ignore: prefer_const_constructors
MyInputField(
title: 'critical',
hint: 'write critical ',
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _criticalController[index],
onSubmit: (value) {
setState(() {
aqltbl.aql![index].critical = value;
_save();
});
},
),
MyInputField(
title: 'majority',
hint: 'write majority ',
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _majorController[index],
onSubmit: (value) {
setState(() {
aqltbl.aql![index].major = value;
_save();
});
},
),
MyInputField(
title: 'minority',
hint: 'write minority ',
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _minorController[index],
onSubmit: (value) {
setState(() {
aqltbl.aql![index].minor = value;
_save();
});
},
),
],
),
),
],
);
}),
),
Container(
height: 270,
width: 300,
margin: const EdgeInsets.only(right: 10, left: 20),
padding: const EdgeInsets.only(
left: 10, bottom: 3, right: 10, top: 5),
decoration: const BoxDecoration(
color: lightBlue,
),
child: Column(
children: [
const Text(
'Summery results',
style: TextStyle(color: medBlueColor),
),
Container(
margin: const EdgeInsets.only(top: 10, bottom: 5),
alignment: Alignment.centerLeft,
child: const Text(
'Results',
style: TextStyle(color: medBlueColor),
),
),
Container(
padding: const EdgeInsets.only(right: 5, left: 5),
decoration: BoxDecoration(
color: whiteColor,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: borderColor,
)),
child: DropdownButtonHideUnderline(
child: DropdownButton<String>(
focusColor: whiteColor,
value: aqltbl.result,
hint: const Text('select result'),
isExpanded: true,
iconSize: 36,
icon: const Icon(Icons.arrow_drop_down),
items: resultsFld.map((res) {
return DropdownMenuItem<String>(
value: res,
child: Text(
res,
style: const TextStyle(
fontFamily: 'tajawal',
fontSize: 15,
color: medBlueColor),
),
);
}).toList(),
onChanged: (val) {
setState(() {
aqltbl.result = val;
});
_save();
},
),
),
),
// aqltbl.result = selRes;
MyInputField(
width: 300,
title: 'information remarks (ir)',
hint: '',
maxLines: 3,
borderColor: borderColor,
textColor: textColor,
hintColor: hintColor,
controller: _irController,
onSubmit: (value) {
aqltbl.ir = value;
_save();
},
),
],
),
),
],
),
),
//Images Container
Container(
height: 400,
padding: const EdgeInsets.all(0),
margin: const EdgeInsets.only(bottom: 10, left: 10),
decoration: const BoxDecoration(color: lightGrey),
child: (aqltbl.images ?? []).isEmpty
? Column(
children: [
Image.asset(
'images/empty-photo.jpg',
height: 300,
),
Container(
margin: const EdgeInsets.only(top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Text('Click'),
Text(
'Camera button',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(' to add new photo'),
],
)),
],
)
: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: (aqltbl.images ?? []).length,
itemBuilder: (context, imgIndex) {
String? _image =
(aqltbl.images ?? [])[imgIndex].name.toString();
inspect('aql image file');
File(_image).exists() == true
? inspect('image exist')
: inspect('not exist: ' + _image);
inspect('_image: ' + _image);
if (aqltbl.images!.length >
_imgCommintControllers.length) {
_imgCommintControllers.add(TextEditingController());
}
_imgCommintControllers[imgIndex].text =
aqltbl.images![imgIndex].imgComment!;
inspect(_imgCommintControllers.length);
return Container(
margin: const EdgeInsets.only(left: 5),
height: 300,
child: Column(
children: [
Stack(
children: [
Image.file(
File(_image),
height: 300,
),
Container(
decoration: const BoxDecoration(
color: medBlueColor,
),
child: IconButton(
onPressed: () {
inspect('clear');
String imgName =
aqltbl.images![imgIndex].name ??
'';
aqltbl.images!.removeAt(imgIndex);
// aqltbl.images!.removeWhere(
// (item) => item.name == imgName);
_imgCommintControllers
.removeAt(imgIndex);
setState(() {});
},
color: whiteColor,
icon: const Icon(Icons.clear)),
)
],
),
MyInputField(
title: 'Write remarks about image',
hint: '',
controller: _imgCommintControllers[imgIndex],
onSubmit: (value) {
aqltbl.images![imgIndex].imgComment = value;
aqltbl.images![imgIndex].name = _image;
_save();
},
),
],
));
}),
),
],
),
),
// --- FloatingActionButton
floatingActionButtonLocation: FloatingActionButtonLocation
.centerDocked, //specify the location of the FAB
floatingActionButton: FloatingActionButton(
backgroundColor: medBlueColor,
onPressed: () {
inspect(aqltbl);
setState(() {
clickedCentreFAB =
!clickedCentreFAB; //to update the animated container
});
},
tooltip: "Centre FAB",
child: Container(
margin: const EdgeInsets.all(15.0),
child: const Icon(Icons.send),
),
elevation: 4.0,
),
// --- bottom action bar
bottomNavigationBar: BottomAppBar(
child: Container(
margin: const EdgeInsets.only(left: 12.0, right: 12.0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
//to leave space in between the bottom app bar items and below the FAB
IconButton(
//update the bottom app bar view each time an item is clicked
onPressed: () {
// updateTabSelection(0, "Home");
Get.to(const MainMenu());
},
iconSize: 27.0,
icon: Image.asset(
'images/logo.png',
color: medBlueColor,
),
),
const SizedBox(
width: 50.0,
),
IconButton(
onPressed: () async {
// updateTabSelection(2, "Incoming");
await _takeImage('gallery');
},
iconSize: 27.0,
icon: const Icon(
Icons.image_outlined,
color: medBlueColor,
),
),
IconButton(
onPressed: () async {
// updateTabSelection(1, "Outgoing");
await _takeImage('camera');
},
iconSize: 27.0,
icon: const Icon(
Icons.camera_alt,
color: medBlueColor,
),
),
],
),
),
//to add a space between the FAB and BottomAppBar
shape: const CircularNotchedRectangle(),
//color of the BottomAppBar
color: Colors.white,
),
);
}
_save() {
inspect('submit');
saveAql(shipmentId, aqltbl);
box.write('aql'+shipmentId.toString(), aqltbl);
}
_takeImage(method) async {
String _imgPath = await imageFromDevice(method);
if (_imgPath != empty) {
ImagesModel imgMdl = ImagesModel();
imgMdl.name = _imgPath;
imgMdl.imgComment = '';
if (aqltbl.images != null) {
// _saveLocaly(close: 0);
setState(() {
aqltbl.images!.add(imgMdl);
_save();
});
}
}
}
Future _sendAqlToServer() async {
try {
var response = await http.post(urlSendProductPhoto, body: {
'aql': json.encode(aqltbl).toString(),
'id': shipmentId.toString(),
});
if (response.statusCode == 200) {
Get.snackbar('Success', 'Image successfully uploaded');
return response.body;
} else {
Get.snackbar('Fail', 'Image not uploaded');
inspect('Request failed with status: ${response.statusCode}.');
return 'empty';
}
} catch (socketException) {
Get.snackbar('warning', 'Image not uploaded');
return 'empty';
}
}
}
Try following the path that it is saying it cannot find in your computer, I had a similar issue, I tried opening an Iphone 12 instead of an Iphone 13 and it worked out the issue, my problem was I inadvertently deleted a few files I shouldn't have.

How to usage Obx() with getx in flutter?

On my UI screen, I have 2 textfields in a column. If textFormFieldEntr is empty, hide textFormFiel. If there is a value in the textFormFieldEntr, let the other textfield be visible. After I set the bool active variable to false in the Controller class, I checked the value in the textFormFieldEntr in the showText class. I'm wrong using obx on the UI screen. The textfields are listed in the _formTextField method. Can you answer by explaining the correct obx usage on the code I shared?
class WordController extends GetxController {
TextEditingController controllerInput1 = TextEditingController();
TextEditingController controllerInput2 = TextEditingController();
bool active = false.obs();
final translator = GoogleTranslator();
RxList data = [].obs;
#override
void onInit() {
getir();
super.onInit();
}
void showText() {
if (!controllerInput1.text.isEmpty) {
active = true;
}
}
ekle(Word word) async {
var val = await WordRepo().add(word);
showDilog("Kayıt Başarılı");
update();
return val;
}
updateWord(Word word) async {
var val = await WordRepo().update(word);
showDilog("Kayıt Başarılı");
return val;
}
deleteWord(int? id) async {
var val = await WordRepo().deleteById(id!);
return val;
}
getir() async {
//here read all data from database
data.value = await WordRepo().getAll();
print(data);
return data;
}
translateLanguage(String newValue) async {
if (newValue == null || newValue.length == 0) {
return;
}
List list = ["I", "i"];
if (newValue.length == 1 && !list.contains(newValue)) {
return;
}
var translate = await translator.translate(newValue, from: 'en', to: 'tr');
controllerInput2.text = translate.toString();
//addNote();
return translate;
}
showDilog(String message) {
Get.defaultDialog(title: "Bilgi", middleText: message);
}
addNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await ekle(word);
getir();
clear();
}
clear() {
controllerInput2.clear();
controllerInput1.clear();
}
updateNote() async {
var word =
Word(wordEn: controllerInput1.text, wordTr: controllerInput2.text);
await updateWord(word);
await getir();
update();
}
}
UI:
class MainPage extends StatelessWidget {
bool _active=false.obs();
String _firstLanguage = "English";
String _secondLanguage = "Turkish";
WordController controller = Get.put(WordController());
final _formKey = GlobalKey<FormState>();
#override
Widget build(BuildContext context) {
controller.getir();
return Scaffold(
drawer: _drawer,
backgroundColor: Colors.blueAccent,
appBar: _appbar,
body: _bodyScaffold,
floatingActionButton: _floattingActionButton,
);
}
SingleChildScrollView get _bodyScaffold {
return SingleChildScrollView(
child: Column(
children: [
chooseLanguage,
translateTextView,
],
),
);
}
AppBar get _appbar {
return AppBar(
backgroundColor: Colors.blueAccent,
centerTitle: true,
title: Text("TRANSLATE"),
elevation: 0.0,
);
}
get chooseLanguage => Container(
height: 55.0,
decoration: buildBoxDecoration,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
firstChooseLanguage,
changeLanguageButton,
secondChooseLanguage,
],
),
);
get buildBoxDecoration {
return BoxDecoration(
color: Colors.white,
border: Border(
bottom: BorderSide(
width: 3.5,
color: Colors.grey,
),
),
);
}
refreshList() {
controller.getir();
}
get changeLanguageButton {
return Material(
color: Colors.white,
child: IconButton(
icon: Icon(
Icons.wifi_protected_setup_rounded,
color: Colors.indigo,
size: 30.0,
),
onPressed: () {},
),
);
}
get secondChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._secondLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
get firstChooseLanguage {
return Expanded(
child: Material(
color: Colors.white,
child: InkWell(
onTap: () {},
child: Center(
child: Text(
this._firstLanguage,
style: TextStyle(
color: Colors.blue[600],
fontSize: 22.0,
),
),
),
),
),
);
}
get translateTextView => Column(
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 2.0),
child: _formTextField,
),
Container(
height: Get.height/1.6,
child: Obx(() {
return ListView.builder(
itemCount: controller.data.length,
itemBuilder: (context, index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
margin: EdgeInsets.only(left: 2.0, right: 2.0, top: 0.8),
child: Container(
color: Colors.white30,
height: 70.0,
padding:
EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
firstText(controller.data, index),
secondText(controller.data, index),
],
),
historyIconbutton,
],
),
),
);
},
);
}),
)
],
);
get _formTextField {
return Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
color: Colors.white30,
height: 120.0,
padding: EdgeInsets.only(left: 16.0, top: 8.0, bottom: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
textFormFieldEntr,
favoriIconButton,
],
),
),
textFormField //burası kapandı
],
),
);
}
get textFormFieldEntr {
return Flexible(
child: Container(
child: TextFormField(
onTap: () {
showMaterialBanner();
},
// onChanged: (text) {
// controller.translateLanguage(text);
// },
controller: controller.controllerInput1,
maxLines: 6,
validator: (controllerInput1) {
if (controllerInput1!.isEmpty) {
return "lütfen bir değer giriniz";
} else if (controllerInput1.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
hintText: "Enter",
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
);
}
void showMaterialBanner() {
ScaffoldMessenger.of(Get.context!).showMaterialBanner(MaterialBanner(
backgroundColor: Colors.red,
content: Padding(
padding: const EdgeInsets.only(top: 30.0),
child: Column(
children: [
TextFormField(
controller: controller.controllerInput1,
maxLines: 6,
onChanged: (text) {
controller.translateLanguage(text);
controller.showText();
},
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
suffixIcon: IconButton(onPressed: () {
FocusScope.of(Get.context!).unfocus();
closeBanner();
}, icon: Icon(Icons.clear),),
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
SizedBox(height: 80.0),
TextFormField(
controller: controller.controllerInput2,
maxLines: 6,
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
],
),
),
actions: [
IconButton(
onPressed: () {
closeBanner();
},
icon: Icon(
Icons.arrow_forward_outlined,
color: Colors.indigo,
size: 36,
),
),
]));
}
void closeBanner() {
ScaffoldMessenger.of(Get.context!).hideCurrentMaterialBanner();
}
// } controller.controllerInput1.text==""?_active=false: _active=true;
get textFormField {
return Visibility(
visible: controller.active,
child: Container(
color: Colors.white30,
height: 120.0,
padding: EdgeInsets.only(left: 16.0, right: 42.0, top: 8.0, bottom: 8.0),
child: Container(
child: TextFormField(
controller: controller.controllerInput2,
maxLines: 6,
validator: (controllerInput2) {
if (controllerInput2!.length > 22) {
return "en fazla 22 karakter girebilirsiniz";
}
return null;
},
decoration: InputDecoration(
contentPadding: const EdgeInsets.symmetric(vertical: 5.0),
),
),
),
),
);
}
FutureBuilder<dynamic> get historyWordList {
return FutureBuilder(
future: controller.getir(),
builder: (context, AsyncSnapshot snapShot) {
if (snapShot.hasData) {
var wordList = snapShot.data;
return ListView.builder(
itemCount: wordList.length,
itemBuilder: (context, index) {
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
),
margin: EdgeInsets.only(left: 8.0, right: 8.0, top: 0.8),
child: Container(
color: Colors.white30,
height: 70.0,
padding: EdgeInsets.only(left: 8.0, top: 8.0, bottom: 8.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
firstText(wordList, index),
secondText(wordList, index),
],
),
historyIconbutton,
],
),
),
);
},
);
} else {
return Center();
}
},
);
}
IconButton get historyIconbutton {
return IconButton(
onPressed: () {},
icon: Icon(Icons.history),
iconSize: 30.0,
);
}
Text firstText(wordList, int index) {
return Text(
"İngilizce: ${wordList[index].wordEn ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w600,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
Text secondText(wordList, int index) {
return Text(
"Türkçe: ${wordList[index].wordTr ?? ""}",
style: TextStyle(
fontWeight: FontWeight.w400,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
}
get favoriIconButton {
return IconButton(
alignment: Alignment.topRight,
onPressed: () async {
bool validatorKontrol = _formKey.currentState!.validate();
if (validatorKontrol) {
String val1 = controller.controllerInput1.text;
String val2 = controller.controllerInput2.text;
print("$val1 $val2");
await controller.addNote();
await refreshList();
}
await Obx(() => textFormField(
controller: controller.controllerInput2,
));
await Obx(() => textFormField(
controller: controller.controllerInput1,
));
},
icon: Icon(
Icons.forward,
color: Colors.blueGrey,
size: 36.0,
),
);
}
FloatingActionButton get _floattingActionButton {
return FloatingActionButton(
onPressed: () {
Get.to(WordListPage());
},
child: Icon(
Icons.app_registration,
size: 30,
),
);
}
Drawer get _drawer {
return Drawer(
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
userAccountsDrawerHeader,
drawerFavorilerim,
drawersettings,
drawerContacts,
],
),
);
}
ListTile get drawerContacts {
return ListTile(
leading: Icon(Icons.contacts),
title: Text("Contact Us"),
onTap: () {
Get.back();
},
);
}
ListTile get drawersettings {
return ListTile(
leading: Icon(Icons.settings),
title: Text("Settings"),
onTap: () {
Get.back();
},
);
}
ListTile get drawerFavorilerim {
return ListTile(
leading: Icon(
Icons.star,
color: Colors.yellow,
),
title: Text("Favorilerim"),
onTap: () {
Get.to(FavoriListPage());
},
);
}
UserAccountsDrawerHeader get userAccountsDrawerHeader {
return UserAccountsDrawerHeader(
accountName: Text("UserName"),
accountEmail: Text("E-mail"),
currentAccountPicture: CircleAvatar(
backgroundColor: Colors.grey,
child: Text(
"",
style: TextStyle(fontSize: 40.0),
),
),
);
}
}
You can simple do it like this
class ControllerSample extends GetxController{
final active = false.obs
functionPass(){
active(!active.value);
}
}
on page
final sampleController = Get.put(ControllerSample());
Obx(
()=> Form(
key: yourkeyState,
child: Column(
children: [
TextFormField(
//some other needed
//put the function on onChanged
onChanged:(value){
if(value.isEmpty){
sampleController.functionPass();
}else{
sampleController.functionPass();
}
}
),
Visibility(
visible: sampleController.active.value,
child: TextFormField(
//some other info
)
),
]
)
)
)

List.Builder giving range error in Flutter

I have added my entire code over here. The getRecords method takes more time to add to the lists and hence my list returns empty at first and so listbuilder fails giving range error and that only range accepted is 0. BTW, Its a Todo app.
InitState :
void initState() {
super.initState();
setState(() {
getRecords();
});
}
Getting from the database
void getRecordsAndDisplay() async {
final records = await Firestore.instance.collection('tasks').getDocuments();
for (var record in records.documents) {
if (record.data['phone'] == '1') {
int len = record.data['task'].length;
if (len != null || len != 0) {
for (int i = 0; i < len; i++) {
String temp = record.data['task'][i];
tasks.add(temp);
}
}
else
continue;
}
else
continue;
}
setState(() {
listView = ListView.builder(
scrollDirection: Axis.vertical,
itemCount: tasks.length,
itemBuilder: (BuildContext context,int index) {
return Container(
margin: EdgeInsets.only(bottom: 10.0),
decoration: BoxDecoration(
color: Colors.deepPurple[700],
borderRadius: BorderRadius.all(Radius.circular(20.0)),
),
child: ListTile(
onTap: (){},
leading: IconButton(
icon: Icon(Icons.delete),
iconSize: 25.0,
color: Colors.white,
onPressed: () {
setState(() {
tasks.removeAt(index);
checkValue.removeAt(index);
updateValue();
});
},
),
title: Text(
'${tasks[index]}',
style: TextStyle(
fontSize: 18.0,
color: Colors.white,
fontWeight: FontWeight.bold,
decoration: checkValue[index]
? TextDecoration.lineThrough
: null,
),
),
trailing: Checkbox(
value: checkValue[index],
activeColor: Colors.white,
checkColor: Colors.deepPurple[700],
onChanged: (bool value) {
setState(() {
checkValue[index] = !checkValue[index];
});
},
),
),
);
},
);
});
}
Scaffold:
return Scaffold(
backgroundColor: Color(0xff8780FF),
body: SafeArea(
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
colors: [Colors.deepPurple[400], Color(0xff6B63FF)])),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(30.0, 30.0, 30.0, 15.0),
decoration: BoxDecoration(boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.2),
spreadRadius: 1.0,
blurRadius: 50.0,
),
]),
child: Icon(
Icons.list,
color: Colors.white,
size: 30.0,
),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
padding: EdgeInsets.only(
bottom: 20.0,
left: 30.0,
),
child: Text(
'Todo List',
style: TextStyle(
color: Colors.white,
fontSize: 35.0,
fontWeight: FontWeight.w900,
),
),
),
Expanded(
child: SizedBox(
width: 20.0,
),
),
IconButton(
padding: EdgeInsets.only(
right: 10.0,
bottom: 20.0,
),
icon: Icon(Icons.add),
iconSize: 30.0,
color: Colors.white,
onPressed: () async {
final resultText = await showModalBottomSheet(
context: context,
builder: (context) => AddTaskScreen(),
isScrollControlled: true);
setState(() {
tasks.add(resultText);
checkValue.add(false);
Firestore.instance
.collection('tasks')
.document('1')
.updateData({
'task': FieldValue.arrayUnion([resultText]),
});
});
},
),
IconButton(
padding: EdgeInsets.only(
right: 10.0,
bottom: 20.0,
),
icon: Icon(Icons.delete_outline),
iconSize: 30.0,
color: Colors.white,
onPressed: () {
setState(() {
tasks.clear();
checkValue.clear();
Firestore.instance
.collection('tasks')
.document('1')
.updateData({
'task': null,
});
});
},
),
],
),
],
),
Flexible(
child: Container(
padding: EdgeInsets.only(left: 10.0, right: 10.0),
height: MediaQuery.of(context).size.height,
child: listView,
),
),
],
),
),
),
);
Please help me out. I am stuck with this for a long time :(
the problem is that in initstate you cannot await for async methods so you should implement a StreamBuilder that wraps your listview..
A streambuilder is a widget that takes a stream and waits for the call completition then when the data is ok shows a widget -> your listview
A little example
StreamBuilder(
stream: YOUR_ASYNC_CALL_THAT_RETURN_A_STREAM,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Container(
alignment: Alignment.center,
child: Text(
"NO ITEMS"
),
);
}
else {
var yourList = snapshot.data.documents;//there you have to do your implementation
return ListView.builder(
itemBuilder: (context, index) => buildItem(index,yourList[index]),
itemCount: yourList.length,
);
}
},
),