I have a textAheadField and successfully get data from it, i call setState so the data can be saved locally in statefullwidget. and i want to store it in database firestore but inside the update method firestore the variable that i want (imageuniversitycollege) is empty and has not been update like in the setstate should be.
This is the textAheadField
String imageuniversitycollege = "";
Widget CollegeBuildTextAhead() {
return Container(
margin: EdgeInsets.symmetric(horizontal: 20, vertical: 8),
child: TypeAheadField<SchoolData?>(
hideSuggestionsOnKeyboardHide: true,
debounceDuration: Duration(milliseconds: 500),
textFieldConfiguration: TextFieldConfiguration(
controller: collegeAheadController,
decoration: InputDecoration(
prefixIcon: Icon(Icons.school),
border: OutlineInputBorder(),
hintText: 'Search your school',
),
),
suggestionsCallback: SchoolApi.getUserSuggestions,
itemBuilder: (context, SchoolData? suggestion) {
final datasugestion = suggestion!;
return ListTile(
leading: Container(
width: 40,
height: 40,
child: Image.network(
datasugestion.image,
fit: BoxFit.cover,
),
),
// leading for image
title: Text(datasugestion.university),
);
},
onSuggestionSelected: (SchoolData? choose) {
final datasugestion = choose!;
collegeAheadController.text = datasugestion.university; //this works fine in the update
final String imageuniversitycollege = datasugestion.image;
setState(() {
final String imageuniversitycollege = datasugestion.image;// this is the data i want
print(imageuniversitycollege); //i print it in here its get the usual link of image
});
},
),
);
}
The usual elevated button
Center(
child: ElevatedButton(
child: const Text(
"Confirm",
),
onPressed: () {
updateEducationCollege();
},
),
)
this is the method update, it works but the image is not filled
Future updateEducationCollege() async {
try {
print(FirebaseAuth.instance.currentUser?.uid);
await FirebaseFirestore.instance
.collection("education")
.doc(FirebaseAuth.instance.currentUser!.uid)
.set({
"uid": FirebaseAuth.instance.currentUser?.uid,
"College": collegeAheadController.text,
"imageCollege": imageuniversitycollege,
}).then((value) => print("Data changed successfully"));
} on FirebaseException catch (e) {
Utils.showSnackBar(e.message);
}
}
The collegeAheadController.text seems fine still successfully retrieve the data like the image bellow
what should i do? to get this data??
Just change
setState(() {
final String imageuniversitycollege = datasugestion.image;
});
to
setState(() {
imageuniversitycollege = datasugestion.image;
});
Instead of updating the existing state variable, you are creating a new local variable. Thats the issue.
Happy coding:)
When you try update your variable you are define new one, change your onSuggestionSelected to this:
onSuggestionSelected: (SchoolData? choose) {
final datasugestion = choose!;
collegeAheadController.text = datasugestion.university;
final String imageuniversitycollege = datasugestion.image;
setState(() {
imageuniversitycollege = datasugestion.image; //<-- change this
print(imageuniversitycollege);
});
},
Related
I am trying to show a loader when a form is submitted to the server so that there isn't another submission of the same form until and unless the API sends back a response. I have tried something like the below code but it just doesn't seem to work as the Circular Progress indicator seems to not show up and rather, the screen remains as it is until the server sends back a response. As a result of this, the user gets confused as to whether or not their requests got submitted, and in the process, they end up posting the same form another time only to find out later that their were multiple submissions. I will include snippets of the code that has the CircularProgressIndicator() to prevent another submission and the widget that has the API call code.
bool isSelected = false;
isSelected
? const CircularProgressIndicator() : Container(
child: Center(
child: AppButtonStyle(
label: 'Submit',
onPressed: () {
if (_key.currentState!.validate()) { //This is the key of the Form that gets submitted
setState(() {
isSelected = true;
});
List<String> date = [
dateFormat.format(_dateTimeStart!).toString(),
dateFormat.format(_dateTimeEnd!).toString()
];
Map<String, dynamic> data = {
'leave_type': _selectedItem,
'dates': date,
'description': add
};
if (kDebugMode) {
print('DATA: $data');
}
Provider.of<LeaveViewModel>(context, listen: false)
.postLeaveRequests(data, context) //This here makes the API call
.then((value) {
setState(() {
isSelected = false;
_textController.clear();
_dateTimeStart = null;
_dateTimeEnd = null;
});
});
}
},
),
),
)
The API module:
class LeaveViewModel with ChangeNotifier {
final leaveRepository = LeaveRequestRepository();
Future<void> postLeaveRequests(dynamic data, BuildContext context) async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String authToken = localStorage.getString('token').toString();
leaveRepository.requestLeave(authToken, data).then((value) {
print('LEAVEEEEEE: $value');
Flushbar(
duration: const Duration(seconds: 4),
flushbarPosition: FlushbarPosition.BOTTOM,
borderRadius: BorderRadius.circular(10),
icon: const Icon(Icons.error, color: Colors.white),
// margin: const EdgeInsets.fromLTRB(100, 10, 100, 0),
title: 'Leave Request Submitted',
message: value.data.toString()
).show(context);
}).onError((error, stackTrace) {
Flushbar(
duration: const Duration(seconds: 4),
flushbarPosition: FlushbarPosition.BOTTOM,
borderRadius: BorderRadius.circular(10),
icon: const Icon(Icons.error, color: Colors.white),
// margin: const EdgeInsets.fromLTRB(100, 10, 100, 0),
title: 'Leave Request Failed',
message: error.toString()
).show(context);
});
}
}
Any help will be appreciated. Also, I'm open to the concept of using easy_loader 2.0.0 instead of CicularProgressIndicator() and would be very glad to read suggestions about it's usage in my code.
One problem in your code seems to be that you define isSelected in your build method. Every time you call setState, the build method is called to regenerate the widgets. And with each new call isSelected gets false as initial value. Define isSelected as class variable, so that it is not always on false.
The more elegant solution would be to work with a FutureBuilder
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
I tried to upload multi images, but it wasn't display preview photos.
Original code is can display only photo, but I modified the code then tried to upload multi images. Still cannot show to me.
Original Code, working well, but just show one image
SizedBox(
height: 250,
child: AspectRatio(
aspectRatio: 487 / 451,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: MemoryImage(_file!),
fit: BoxFit.fill,
alignment: FractionalOffset.topCenter,
),
),
),
),
),
Then I tried to modified to this one
Expanded(
child: GridView.builder(
itemCount: selectedFiles.length,
gridDelegate:
const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemBuilder: (BuildContext context, int index) {
return Image.file(File(selectedFiles[index].path));
},
),
),
It wasn't show to me.
I can got the image list
Future<void> selectImage() async {
if (selectedFiles != null) {
selectedFiles.clear();
}
try {
final List<XFile>? imgs = await _picker.pickMultiImage();
if (imgs!.isNotEmpty) {
selectedFiles.addAll(imgs);
}
print("image list : " + imgs.length.toString());
} catch (e) {
print(e.toString());
}
setState(() {});
}
Or I need to modify this code??
SimpleDialogOption(
padding: const EdgeInsets.all(20),
child: const Text('Choose from gallery'),
onPressed: () async {
Navigator.of(context).pop();
Uint8List file = await pickImage(ImageSource.gallery);
// final List<XFile>? imgs = await _picker.pickMultiImage();
// if (imgs!.isNotEmpty) {
// selectedFiles.addAll(imgs);
// }
setState(() {
_file = file;
});
},
),
For the GridView to display images the Ui has to rebuild
So when you add images to your list
if (imgs!.isNotEmpty) {
selectedFiles.addAll(imgs);
}
you dont notify the UI to rebuild.
you can call an empty setstate below the selectedFiles to force UI to rebuild.
if (imgs!.isNotEmpty) {
selectedFiles.addAll(imgs);
setState((){
})
}
For example when picking a single file
File? myfile;
pickFile()async{
FilePickerResult? result = await FilePicker.platform.pickFiles();
if (result != null) {
File file = File(result.files.single.path);
setState((){
myFile=file;
})
} else {
// User canceled the picker
}}
I am new flutter .I want to update new version app in playstore to show a message dialog to user to update the new version and I used the plugin version_check 0.2.0.
When the user has already updated, but it still displays Message dialog the same. How not to show message dialog after update.Who can help me?
This my Code
This my Code
This my Code
As everything is not clear in the question, you should follow given steps to achieve the same.
Step 1. Go to Remote Config in firebase and add few parameters shown in the image and then publish it.
Step 2. Create a function VersionCheck and _showVersionDialog as follows:
versionCheck(){
//Get Current installed version of app
WidgetsBinding.instance.addPostFrameCallback((_) async {
final PackageInfo info = await PackageInfo.fromPlatform();
double currentVersion = double.parse(info.version.trim().replaceAll(".", ""));
//Get Latest version info from firebase config
final RemoteConfig remoteConfig = await RemoteConfig.instance;
try {
// Using default duration to force fetching from remote server.
await remoteConfig.fetch(expiration: const Duration(seconds: 0));
await remoteConfig.activateFetched();
remoteConfig.getString('force_update_current_version');
double newVersion = double.parse(remoteConfig
.getString('force_update_current_version')
.trim()
.replaceAll(".", ""));
if (newVersion > currentVersion) {
setState(() {
versionCode = remoteConfig.getString('force_update_current_version');
aboutVersion = remoteConfig.getString('update_feature');
});
_showVersionDialog(context);
}
} on FetchThrottledException catch (exception) {
// Fetch throttled.
print(exception);
} catch (exception) {
print('Unable to fetch remote config. Cached or default values will be '
'used');
}
});
}
_showVersionDialog(context) async {
await showDialog<String>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
String title = "Update Available";
String message =
"About Update: \n";
return ButtonBarTheme(
data: ButtonBarThemeData(alignment: MainAxisAlignment.center),
child: new AlertDialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(title),
Text("v"+versionCode),
],
),
content: Container(
height: 80,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(message,style: TextStyle(fontWeight: FontWeight.bold),),
Text(aboutVersion),
],
),
),
actions: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: new Text(
'Update',
style: TextStyle(color: Colors.white),
),
color: Color(0xFF121A21),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
onPressed: () {
_launchURL(PLAY_STORE_URL);
},
),
),
],
),
);
},
);
}
Step 3. Call VersionCheck in init function of your main screen as follows.
#override
void initState() {
Future.delayed(const Duration(milliseconds: 5000), () {
if(mounted){
setState(() {
versionCheck();
});
}
});
super.initState();
}
Step 4. Whenever you want the update dialog to appear on screen just increase the version code value in remote config of firebase than your actual version code value.
This will help you to achieve what you want.
Strings of element inside a List becomes empty when passing as an argument.
It was working before. I don't know what happened that it stopped working, and started passing empty.
I have a model called SubjectiveList, it is the list I am talking about.
class SubjectiveList {
String id;
String name;
List<Item> items;
SubjectiveList({this.id, this.name, this.items});
}
This list has the property items. What becomes empty is the properties inside the Item object.
class Item {
String id;
String name;
Content content;
Item({this.id, this.name, this.content});
}
On the debugger, The newList instance appears fine, with the object names (ps: the ID is okay to be null at this point because it will come from Firestore Database later)
Here is the code with the screenshots:
Future<dynamic> showListInfoDialog() {
final userData = Provider.of<UserData>(context, listen: false);
GlobalKey<FormState> _addListInfoFormKey = GlobalKey<FormState>();
final ValueNotifier<int> tabIndex =
Provider.of<ValueNotifier<int>>(context, listen: false);
TempListViewModel tempList =
Provider.of<TempListViewModel>(context, listen: false);
return showDialog(
context: context,
child: SimpleDialog(
title: Text("List Info"),
children: <Widget>[
Padding(
padding: const EdgeInsets.all(defaultSpacing),
child: Form(
key: _addListInfoFormKey,
child: Column(
children: <Widget>[
TextFormField(
onChanged: (val) => tempList.setListName(val),
validator: (val) => val.isEmpty ? 'Write a name' : null,
decoration: InputDecoration(
prefixIcon: Icon(Icons.featured_play_list),
labelText: "List Name",
),
),
SizedBox(height: defaultSpacing),
SizedBox(
width: double.infinity,
child: RaisedButton(
child: Text("Create List"),
color: successColor,
onPressed: () {
if (_addListInfoFormKey.currentState.validate()) {
final newList = SubjectiveList(
name: tempList.list.name,
items: tempList.list.items);
DatabaseService(uid: userData.uid)
.addListToDatabase(newList); // <-- HERE
tempList.init();
tabIndex.value = 0;
Navigator.of(context).pop();
}
},
),
)
],
),
),
),
],
),
);
}
And then it appears empty when coming to the function!!
Future addListToDatabase(SubjectiveList list) async { <-- HERE
DocumentReference listDocument =
await userDocument.collection('lists').add({'name': list.name});
[...]
}
Thanks #edenar
Now I understand what happened. In Flutter the line "final newList = SubjectiveList(name: tempList.list.name, items: tempList.list.items);" makes a pointer reference, and not an declaration of the current value. So, when it goes to the next line and executes tempList.init() it is clearing the list before getting the argument in the function.
So it worked putting await in that line.
I'm trying to build a text field with autocomplete feature. And I'm using AutoComplete TextField package.
I have Users model class with fromMap and toMap methods. There's function which retrieves users form database and returns list of users List<Users>.
Here's the code which builds autocomplete field:
AutoCompleteTextField searchTextField = AutoCompleteTextField<Users>(
key: key,
clearOnSubmit: false,
suggestions: users,
style: TextStyle(color: Colors.black, fontSize: 16.0),
decoration: InputDecoration(
contentPadding: EdgeInsets.fromLTRB(10.0, 30.0, 10.0, 20.0),
hintText: "Search Name",
hintStyle: TextStyle(color: Colors.black),
),
itemFilter: (item, query) {
return item.name.toLowerCase().startsWith(query.toLowerCase());
},
itemSorter: (a, b) {
return a.name.compareTo(b.name);
},
itemSubmitted: (item) {
setState(() {
searchTextField.textField.controller.text = item.name;
});
},
itemBuilder: (context, item) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
item.name,
),
],
);
},
);
Q. Am I missing something or doing wrong?
NOTE:
The users object have list of users in correct format, I've printed to verify that.
As #pskink mentioned,
you are using autocomplete_textfield? i had a lot of problems with it, that disappeared when i switched to flutter_typeahead (much better documented package)
So I considered his suggestion, and move to flutter_typeahead package.
final TextEditingController _typeAheadController = TextEditingController();
List<String> usersList;
//find and create list of matched strings
List<String> _getSuggestions(String query) {
List<String> matches = List();
matches.addAll(usersList);
matches.retainWhere((s) => s.toLowerCase().contains(query.toLowerCase()));
return matches;
}
//gets user list from db
void _getUsersList() async {
usersList = await databaseHelper.getUsersList();
}
//the above code is defined in the class, before build method
//builds the text field
TypeAheadFormField(
textFieldConfiguration: TextFieldConfiguration(
controller: _typeAheadController,
decoration: InputDecoration(labelText: 'Select a User'),
suggestionsCallback: (pattern) {
return _getSuggestions(pattern);
},
itemBuilder: (context, suggestion) {
return ListTile(
title: Text(suggestion),
);
},
transitionBuilder: (context, suggestionsBox, controller) {
return suggestionsBox;
},
onSuggestionSelected: (suggestion) {
_typeAheadController.text = suggestion;
},
validator: (val) => val.isEmpty
? 'Please select a user...'
: null,
onSaved: (val) => setState(() => _name = val),
),
//function that pulls data from db and create a list, defined in db class
//not directly relevant but it may help someone
Future<List<String>> getUsersList() async {
Database db = await instance.database;
final usersData = await db.query("users");
return usersData.map((Map<String, dynamic> row) {
return row["name"] as String;
}).toList();
}
PS: One thing I miss about autocomplete_textfield is the way that we can pass multiple parameters, as we can inherit from our own custom model e.g user model. I know it is possible with this, but I'm new to this so still unable to make it work! :(
I was having the same problem, the solution was to put a bool and show a CircularProgressIndicator until all the data in the list is loaded, and thus rendering the AutoCompleteTextField
Ex.:
_isLoading
? CircularProgressIndicator ()
: searchTextField = AutoCompleteTextField <User> (your component here)