that data disapear.but i want whenever i hit on delete button it remove immediately not restart the application.how i solve this problem any one sugget me?
Here init state code
#override
void initState() {
super.initState();
setState(() {
getPostsData();
});
controller.addListener(() {
double value = controller.offset / 119;
setState(() {
topContainer = value;
closeTopContainer = controller.offset > 50;
});
});
_currentScreen();
}
Here is my delete method code
void _delete(BuildContext context, int id) async {
int result = await dbHelper.deletedata(id);
if (result != 0) {
_showSnackBar(context, 'Data Deleted Successfully');
updateListView();
}
}
Here is my update list code
void updateListView() {
final Future<Database> dbFuture = dbHelper.initializeDatabase();
dbFuture.then((database) {});
}
I think adding setState to updateListView() should do it.
void updateListView() {
final Future<Database> dbFuture = dbHelper.initializeDatabase();
dbFuture.then((database) {});
setState((){});
}
Edit: Looks like you only get the data of your database once in initState. Maybe you need to reexecute the function that gets the data everytime you delete something.
Call getPostsData in updateListView.
void updateListView() {
final Future<Database> dbFuture = dbHelper.initializeDatabase();
dbFuture.then((database) {});
getPostsData();
}
Not the base way but you can add a button for refresh the list after deletion and call setState with getPostsData which will refresh items. For better solution you can use provider and notify listeners each time when you make deletion.
Related
I'm trying to get datas from api and add them a list. But at this moment, I see datas i got but I can't get it out of the function. What should i do?
function
List<dynamic> xxx = [];
#override
void initState() {
super.initState();
Future<List<dynamic>> fetchCompanies(List<dynamic> datas) async {
var response = await Dio().get(CompaniesPath().url);
if (response.statusCode == HttpStatus.ok) {
Map<String, dynamic> company = jsonDecode(response.data);
for (int i = 0; i < company['Data'].length; i++) {
datas.add(company['Data'][i]);
}
//print(datas); //=> I see datas here
} else {
throw Exception();
}
return datas;
}
print(fetchCompanies(xxx));
}
When I run print(fetchCompanies(xxx)); I got "Instance of 'Future<List<dynamic>>'". How can i get data inside fetchCompanies to my xxx list?
You're trying to print future instance of List that's why you got
Instance of Future<List>
You have to wait until function finish executing.
Catch here is you can't call wait in initState() so you have to use .then method
try this:
fetchCompanies(xxx)
.then((result) {
print("result: $result");
});
It should already work fine like it is. But you probably want to call a setState to refresh the page. Try this:
#override
void initState() {
super.initState();
Future<List<dynamic>> fetchCompanies(List<dynamic> datas) async {
var response = await Dio().get(CompaniesPath().url);
if (response.statusCode == HttpStatus.ok) {
Map<String, dynamic> company = jsonDecode(response.data);
for (int i = 0; i < company['Data'].length; i++) {
datas.add(company['Data'][i]);
}
//print(datas); //=> I see datas here
setState(() {}); // added this
} else {
throw Exception();
}
return datas;
}
print(fetchCompanies(xxx));
}
I need to persist value from range slider to shared preferences, when user leaves page with sliders, it will still save value, not without resetting to default settings (default is 1).
I am trying to make things like that:
#override
void initState() {
// _loadSlider();
super.initState();
}
#override
void dispose() {
_debounce?.cancel();
super.dispose();
}
var _currentRangeValues = const RangeValues(1, 16);
void _loadSlider() async {
final prefs = await SharedPreferences.getInstance();
setState(() {
_currentRangeValues = (prefs.getStringList('sliderGain') ??
[
_currentRangeValues.start.round().toString(),
_currentRangeValues.end.toString()
]) as RangeValues;
});
}
// change slider value to value
void _changeSlider(RangeValues value) {
setState(() {
_currentRangeValues = value;
});
}
// store slider value
void _storeSlider() async {
final prefs = await SharedPreferences.getInstance();
prefs.setStringList('sliderGain', [
_currentRangeValues.start.round().toString(),
_currentRangeValues.end.round().toString()
]);
}
But I'm getting an error
RangeValues is not subtype of type List
How to resolve this issue?
I found what the issue was about my slider and attempts to save data from it to sharedprefernces. So it needs to convert to List after declaring the range value variable. After that, I made small changes in the code and put data from the declared list into the get string, and after that everything worked. Thanks to the previous commenter for the tip.
void _loadSlider() async {
final prefs = await SharedPreferences.getInstance();
List<String> valuesString = [currentRange.start.round().toString(), currentRange.end.round().toString() ];
setState(() {
valuesString = (prefs.getStringList('sliderGain') ??
[
valuesString.toString()
]);
print(valuesString);
});
}
I am using the shared_preferences within my app to save some data
but they only update the second time I open them
prefs.setInt is Future method, try putting await before all of it.
async{
final prefs = await SharedPreferences.getInstance ();
///others
await prefs.setInt ('s$current month $current year', s);
setState (() { });
}
And create another method to fetch data on initState like
fetchData()async{
final prefs = await SharedPreferences.getInstance ();
hours = prefs.getInt(...);
///....
setState(() { });
}
#override
void initState() {
super.initState();
fetchData();
}
I have these methods, for some reason fetchItems is being called first before initPosition, how come dart wont wait for it to finish and proceeds to the second method? I've added async/await but it still doesn't work. I've also checked my backend logs to confirm this. Am I doing something wrong?
Future<void> initPosition() async {
if (_latitude != null && _longitude != null) {
await Socket.updatePosition(
lat: 51,
lon: 17,);
}
}
Future<void> initMarkers() async {
await initPosition();
await Provider.of<Items>(context, listen: false)
.fetchItems();
}
void initMapState() async {
await getCurrentLocation().then((_) async {
await initMarkers();
setState(() {
_loaded = true;
});
});
}
#override
void initState() {
super.initState();
_location.enableBackgroundMode(enable: false);
WidgetsBinding.instance?.addPostFrameCallback((_) {
initMapState();
});
}
Future<void> fetchItems() async {
itemList = await repository.getItemList();
notifyListeners();
}
Working with multiple asynchronous functions inside Futures depends on whether one is finished or not, not every single one. For this, you can call the "whenComplete" method so you can assure that your future function have finished running. Like this:
For your initMarkers() function:
Future<void> initMarkers() async {
await initPosition().whenComplete((){
Provider.of<Items>(context, listen: false)
.fetchItems();
});
}
For your initMapState() function:
void initMapState() async {
await getCurrentLocation().whenComplete(() async {
await initMarkers().whenComplete((){
setState(() {
_loaded = true;
});
});
});
}
Keep in mind that, in your code, you are not working with the returning value of your getCurrentLocation() function, so instead of using the "then" method use the "whenComplete" method, assuring that you changed or returned your values with this function. Finally, for the initState(), make the function body with asynchronous:
#override
void initState() {
super.initState();
_location.enableBackgroundMode(enable: false);
WidgetsBinding.instance?.addPostFrameCallback((_) async {
initMapState();
});
}
This should work.
I tried to build a simple application, which shoul save and output a value whith shared_preferences. I tried to save an int, but it doesnt´t work. It could be, that the mistake is because of I tried to "convert" the code a youtuber did with a String instead of an int. Can anybody find my mistake? Below is the change code I tried.
int lastLoginInt = 1;
String nameKey = "_key_name";
#override
void initState() {
super.initState();
}
Future<bool> saveLastLoginInt() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
return await preferences.setInt(nameKey, lastLoginInt);
}
Future<int> loadLastLoginInt() async {
SharedPreferences preferences = await SharedPreferences.getInstance();
return preferences.getInt(nameKey);
}
setLastLoginInt() {
loadLastLoginInt().then((value) {
setState(() {
lastLoginInt = value;
});
});
}
You are not calling functions.
Probably you should do this at your initState() function..like this..
#override
void initState() {
super.initState();
saveLastLoginInt();
}
Then use setLastLoginInt() where needed.