我想檢查客戶端是否包含一個 id,并找出它是否已登錄,以便在小部件回傳時對其進行修改,但它總是停在 SharedPrefences 并執行構建,將地址回傳為 false,即使它已記錄。
class _ScheduleStateService extends State<ScheduleService> {
int clientId = 0;
//constructor
_ScheduleStateService(this.roboSelecionado) {
_userAuthenticated();
}
Future _userAuthenticated() async {
SharedPreferences pref = await SharedPreferences.getInstance();
clientId = pref.getInt("cliente_id") ?? 0;
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: const Text('Agendamento'),
),
body: Form(
key: _formKey,
child: ListView(
children:
(clientId != 0)
? Column(
children: [
Padding(
padding: const EdgeInsets.all(8),
child: Card(
elevation: 4,
child: SizedBox(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
keyboardType: TextInputType.text,
controller: enderecoController,
decoration: const InputDecoration(
labelText: 'Endere?o',
enabled: false,
border: InputBorder.none,
labelStyle: TextStyle(
color: Color(0xFFE84505),
fontSize: 18,
fontWeight: FontWeight.w600)),
),
),
),
),
)
],
)
: Column(),
我知道這與 Fure、Async 和 Await 相關,但到目前為止我找不到解決方案!
uj5u.com熱心網友回復:
setState當您希望重新構建小部件以回應狀態更改時,您需要呼叫:
Future<void> _userAuthenticated() async {
SharedPreferences pref = await SharedPreferences.getInstance();
// Never call setState after an asynchronous gap without
// ensuring that the widget is still mounted. Calling setState
// on an unmounted widget will cause an exception to be thrown!
if (!mounted) {
return;
}
setState(() {
clientId = pref.getInt("cliente_id") ?? 0;
});
}
}
initState您還應該從而不是從建構式執行此類操作:
_ScheduleStateService(this.roboSelecionado);
@override
void initState() {
super.initState();
_userAuthenticated();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/530606.html
標籤:扑镖异步等待小部件未来
