我想按 Id 更新数据,我有 userId、姓名和所有详细信息,如果我想根据用户 Id 更改任何用户详细信息,那么我将无法更新数据,并且我正在获取文本表单字段上方的值。请检查我的更新数据函数和代码并帮助,我是 flutter 的新手。
Future<DataDetails> getDataa() async {
final response = await http.get(
Uri.parse("get url"));
if(response.statusCode == 200) {
var temp = DataDetails.fromJson(jsonDecode(response.body));
return temp;
}
return DataDetails.fromJson(jsonDecode(response.body)) ;
}
Future<DataDetails> updateData(String cardName,String name,String designation,String
company,String address,String email,String phone) async {
var edata = {
"id": '$id',
"cardName": cardName,
"name": name,
"designation": designation,
"company": company,
"address": address,
"email": email,
"phone": phone,
};
var ebody = jsonEncode(edata);
final response = await http.put(
Uri.parse('put url'),
body: ebody,
headers: {
'Content-Type': 'application/json-patch+json',
}
);
if (response.statusCode == 200) {
return DataDetails.fromJson(jsonDecode(response.body));
}
else {
throw Exception('Failed to update Data.');
}
}
上面的代码从数据库中获取价值并更新。
这段代码我在数据库中输入了更新的新值,但在这段代码中我没有在文本表单字段中获取旧值。
//initState
late Future<DataDetails> _futureData;
@override
void initState() {
super.initState();
_futureData = getDataa();
}
FutureBuilder(
future: _futureData,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasData) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text('${snapshot.data!.cardName}'),
TextFormField(
controller: _cardnameController,
decoration: const InputDecoration(
hintText: 'Enter Card Name',
border: OutlineInputBorder()
),
),
//Update button call:
ElevatedButton(
onPressed: () {
setState(() {
_futureData = updateData(
_cardnameController.text,
_nameController.text,
_roleController.text,
_companyController.text,
_addressController.text,
_phoneController.text,
_emailController.text,
);
});
},
child: Text('Update'),
),
我是 Flutter 的新手请帮忙, 谢谢
试试这个...
FutureBuilder(
future: _futureData,
builder: (context, snapshot) {
if (snapshot.hasData) {
final data = snapshot.data as DataDetails;
//update the text of controller here
_controller.text = data.name;
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(data.id.toString()),
TextFormField(
controller: _controller,
decoration: const InputDecoration(
hintText: 'Enter Card Name',
border: OutlineInputBorder()
),
)
],
);
}
return const Center(
child: Text("Loading data..."),
);
},
)
根据您的描述,该值未显示在 TextFormField 中。 TextFormField 中的值通过控制器进行管理。所以只需将 initstate 中的值初始化为:_cardnameController.text=cardname.toString;。希望它对你有用。