I have a shared data that contain mobile no of customer,in my profile,that need to be filled with in textfield when i open profile page,i'm getting the data from shard preference data,when i load data to textfield it's throws error
TextEditingController mobile = TextEditingController();
void initState() {
getMobile();
}
Get data From Sharedpreference
Future<String> getMobile() async {
Future notificatinstatus = SharedPrefrence().getUserMobile();
notificatinstatus.then((data) async {
var mobile_no=data;
mobile_no.text=mobile;
return mobile;
});
}
I think is better like this:
var mobileController = TextEditingController();
getMobile() async {
Future notificatinstatus = SharedPrefrence().getUserMobile();
notificatinstatus.then((data) async {
var mobile_no=data;
setState(() {
if(mobile_no.isNotEmpty){
mobileController.text = mobile_no;
}
});
});
}
#override
void initState() {
super.initState();
getMobile();
}
Related
I am writing a simeple todo list app, the todo item stored in sqlite
sqflite: ^2.0.0+3 right now. I want to load the sqlite todo data before loading the flutter page, this is my initial code looks like in flutter:
class _HomePageState extends State<HomePage> {
GlobalKey _inputViewKey = GlobalKey();
List<Todo> _todos = [];
#override
void initState() {
var _db = DBProvider.db;
_todos = await _db.getAllTodo();
super.initState();
}
}
and this is the function to load data from database:
Future<List<Todo>> getAllTodo() async {
final db = await database;
var result = await db.query('Todo');
return result.map((it) => Todo.fromJson(it)).toList();
}
the IDE told that I should add async in the initial function. When I add the async function, the initial function could not work. What should I do to make it work? how to initial the async data before the HomePage?
You cant mark async on inistate. You can try this
class _HomePageState extends State<HomePage> {
GlobalKey _inputViewKey = GlobalKey();
List<Todo> _todos = [];
#override
void initState() {
var _db = DBProvider.db;
getAllTodo();
super.initState();
}
}
And in the method
getAllTodo() async {
final db = await database;
var result = await db.query('Todo');
_todos = result.map((it) => Todo.fromJson(it)).toList();
setState((){});
}
Future<void> setEmpId(String empId) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString(this.empId, empId);
}
Future<String> getEmpId() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String empId;
empId = await prefs.getString(this.empId) ?? '';
return empId;
}
Prefs().setEmpId(state.empVerifyEntity.employee.empId);//set empId from api
In Another Class:
class Page extends State<Page>{
Future<void> getEmpId() async {
String empId = await Prefs().getEmpId().toString();
print("----------->>>>>>>>$empId");
}
#override
void initState() {
super.initState();
getEmpId();
}
}
Here I'm getting instance of future, I tried every method like .then(value) Each and every method I'm getting instance of future. how to data correctly?
The problem you have is due to the fact that your initState method is synchronous and the method in which you are getting the value for EmpId isn't.
Therefore, it is not waiting for the result of the call.
You can accomplish this in several ways:
Add a then clause to the call of getEmpId
#override
void initState() {
super.initState();
getEmpId().then((result) {
//your logic here
)
}
Add a PostFrameCallback
#override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_){
getEmpId();
});
}
I have a getx controller and a method to update data in the database, I just wonder that how can I refresh of update the UI constantly after fetching the API? Here is my controller
class AdditionalContactController extends GetxController {
var additionalContactList = <AdditionalContact>[].obs;
var isLoading = true.obs;
UserController _userController = Get.find();
#override
void onInit() {
super.onInit();
_userController.getMail().then((value) async {
await _userController.getUser(value);
getAdditionalContacts(_userController.user.value.id);
});
}
//Update contact
Future<bool> updateContact({...}) async {
var response = await http.post(
Uri.parse(
"https://..."),
body: {
...
});
var jsonData = jsonDecode(response.body);
if (jsonData == "failed") {
return false;
}
return true;
}
}
you can use the ever worker to call a method that executes every time an Rx have assigned with a new value:
class AdditionalContactController extends GetxController {
var additionalContactList = <AdditionalContact>[].obs;
#override
void onInit() {
super.onInit();
ever(additionalContactList, methodToExecute)
});
}
methodToExecute(list) {
/* Code that will execute every time the additionalContactList changes */
}
now everytime additionalContactList is changed like as example if we assign a new List to it:
additionalContactList.value = [];
Then the methodToExecute() will be executed automatically, and will do every single time.
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.
Class 1
#override
void initState() {
super.initState();
text =DemoLocalizations.of(context).trans('connection');
}
Class 2 (DemoLocalizations)
Future<bool> load() async {
String data = await rootBundle.loadString('locale/i18n_${locale.languageCode}.json');
Map<String, dynamic> _result = json.decode(data);
this._sentences = new Map();
_result.forEach((String key, dynamic value) {
this._sentences[key] = value.toString();
});
return true;
}
Return
So the question is: How can i load custom string (internazionalization) when screen load (oninit)?
Use didChangeDependencies instead of initState.
It is called once after widget creation and again when the state of DemoLocalizations is changed.