我創建了這個表單來向 API 提交資料。
但是有什么不對就有一個錯誤。我宣告變數可以為空,但這個錯誤仍然出現在我身上。
我不知道有什么問題。
注意:我不僅想解決這個錯誤,還想了解我錯過了什么。
你能解釋一下嗎?
匯入“飛鏢:異步”;匯入“飛鏢:轉換”;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
//import package file manually
void main() => runApp(listHouse());
class listHouse extends StatelessWidget {
const listHouse({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.red, //primary color for theme
),
home: WriteSQLdata() //set the class here
);
}
}
class WriteSQLdata extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return WriteSQLdataState();
}
}
class WriteSQLdataState extends State<WriteSQLdata> {
//text controller for TextField
TextEditingController namectl = TextEditingController();
TextEditingController desciptionctl = TextEditingController();
TextEditingController addrctl = TextEditingController();
TextEditingController image_urlctl = TextEditingController();
TextEditingController pricectl = TextEditingController();
bool? error, sending, success;
String? msg;
// do not use http://localhost/ for your local
// machine, Android emulation do not recognize localhost
// insted use your local ip address or your live URL
// hit "ipconfig" on Windows or "ip a" on Linux to get IP Address
@override
void initState() {
error = false;
sending = false;
success = false;
msg = "";
super.initState();
}
Future<void> sendData() async {
var phpurl = Uri.parse("https://homeshouse.000webhostapp.com/create.php");
var res = await http.post(phpurl, body: {
"name": namectl.text,
"desciption": desciptionctl.text,
"addr": addrctl.text,
"image_url": image_urlctl.text,
"price": pricectl.text,
}); //sending post request with header data
if (res.statusCode == 200) {
print(res.body); //print raw response on console
var data = json.decode(res.body); //decoding json to array
if (data["error"]) {
setState(() {
//refresh the UI when error is recieved from server
sending = false;
error = true;
msg = data["message"]; //error message from server
});
} else {
namectl.text = "";
desciptionctl.text = "";
addrctl.text = "";
image_urlctl.text = "";
pricectl.text = "";
//after write success, make fields empty
setState(() {
sending = false;
success = true; //mark success and refresh UI with setState
});
}
} else {
//there is error
setState(() {
error = true;
msg = "Error during sendign data.";
sending = false;
//mark error and refresh UI with setState
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("List Your House"),
backgroundColor: Colors.redAccent), //appbar
body: SingleChildScrollView(
//enable scrolling, when keyboard appears,
// hight becomes small, so prevent overflow
child: Container(
padding: EdgeInsets.all(20),
child: Column(
children: <Widget>[
Container(
child:Text(error?msg:"Enter House Information"),
//if there is error then sho msg, other wise show text message
),
Container(
child:Text(success?"Write Success":"send data"),
//is there is success then show "Write Success" else show "send data"
),
Container(
child: TextField(
controller: namectl,
decoration: InputDecoration(
labelText: "House Name:",
hintText: "Enter House name",
),
)), //text input for name
Container(
child: TextField(
controller: desciptionctl,
decoration: InputDecoration(
labelText: "desciption:",
hintText: "Enter house desciption",
),
)), //text input for address
Container(
child: TextField(
controller: addrctl,
decoration: InputDecoration(
labelText: "address:",
hintText: "Enter house address",
),
)), //text input for class
Container(
child: TextField(
controller: image_urlctl,
decoration: InputDecoration(
labelText: "House Image:",
hintText: "Enter image_urlctl url",
),
)), //text input for roll no
Container(
child: TextField(
controller: pricectl,
decoration: InputDecoration(
labelText: "House price:",
hintText: "Enter House price",
),
)), //text input for roll nox
Container(
margin: EdgeInsets.only(top: 20),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () async {
//if button is pressed, setstate sending = true, so that we can show "sending..."
setState(() {
sending = true;
});
await sendData();
clearfields();
},
child: Text(
sending? "Sending...":"SEND DATA",
// "Sending",
//if sending == true then show "Sending" else show "SEND DATA";
),
// color: Colors.redAccent,
// colorBrightness: Brightness.dark,
//background of button is darker color, so set brightness to dark
)))
],
))),
);
}
void clearfields() {
namectl.clear();
desciptionctl.clear();
addrctl.clear();
image_urlctl.clear();
pricectl.clear();
}
}
uj5u.com熱心網友回復:
sending可以為 null,并且 Dart 不會將 null 視為可以在三元組中使用的虛假值。如果您確定此時它sending不為空,您可以像這樣重寫您的三元:
sending! ? "Sending..." : "SEND DATA",
或者,如果您不確定它是否為空。
sending == true ? "Sending..." : "SEND DATA",
uj5u.com熱心網友回復:
在您的代碼error, sending, success, msg中,所有這些變數都是可選的,這意味著您可以獲得 value 或 null 作為值。
Dart 不會將 null 值視為 false。您只需要給出 true 是 false 值。
更新代碼:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
//import package file manually
void main() => runApp(const ListHouse());
class ListHouse extends StatelessWidget {
const ListHouse({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.red, //primary color for theme
),
home: WriteSQLdata() //set the class here
);
}
}
class WriteSQLdata extends StatefulWidget {
const WriteSQLdata({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return WriteSQLdataState();
}
}
class WriteSQLdataState extends State<WriteSQLdata> {
//text controller for TextField
TextEditingController namectl = TextEditingController();
TextEditingController desciptionctl = TextEditingController();
TextEditingController addrctl = TextEditingController();
TextEditingController image_urlctl = TextEditingController();
TextEditingController pricectl = TextEditingController();
bool? error, sending, success;
String? msg;
// do not use http://localhost/ for your local
// machine, Android emulation do not recognize localhost
// insted use your local ip address or your live URL
// hit "ipconfig" on Windows or "ip a" on Linux to get IP Address
@override
void initState() {
error = false;
sending = false;
success = false;
msg = '';
super.initState();
}
Future<void> sendData() async {
var phpurl = Uri.parse('https://homeshouse.000webhostapp.com/create.php');
var res = await http.post(phpurl, body: {
'name': namectl.text,
'desciption': desciptionctl.text,
'addr': addrctl.text,
'image_url': image_urlctl.text,
'price': pricectl.text,
}); //sending post request with header data
if (res.statusCode == 200) {
print(res.body); //print raw response on console
var data = json.decode(res.body); //decoding json to array
if (data['error']) {
setState(() {
//refresh the UI when error is recieved from server
sending = false;
error = true;
msg = data['message']; //error message from server
});
} else {
namectl.text = '';
desciptionctl.text = '';
addrctl.text = '';
image_urlctl.text = '';
pricectl.text = '';
//after write success, make fields empty
setState(() {
sending = false;
success = true; //mark success and refresh UI with setState
});
}
} else {
//there is error
setState(() {
error = true;
msg = 'Error during sendign data.';
sending = false;
//mark error and refresh UI with setState
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('List Your House'),
backgroundColor: Colors.redAccent), //appbar
body: SingleChildScrollView(
//enable scrolling, when keyboard appears,
// hight becomes small, so prevent overflow
child: Container(
padding: const EdgeInsets.all(20),
child: Column(
children: <Widget>[
Text(error == true ? msg ?? '' : 'Enter House Information'),
Text(success == true ? 'Write Success' : 'send data'),
TextField(
controller: namectl,
decoration: const InputDecoration(
labelText: 'House Name:',
hintText: 'Enter House name',
),
), //text input for name
TextField(
controller: desciptionctl,
decoration: const InputDecoration(
labelText: 'desciption:',
hintText: 'Enter house desciption',
),
), //text input for address
TextField(
controller: addrctl,
decoration: const InputDecoration(
labelText: 'address:',
hintText: 'Enter house address',
),
), //text input for class
TextField(
controller: image_urlctl,
decoration: const InputDecoration(
labelText: 'House Image:',
hintText: 'Enter image_urlctl url',
),
), //text input for roll no
TextField(
controller: pricectl,
decoration: const InputDecoration(
labelText: 'House price:',
hintText: 'Enter House price',
),
), //text input for roll nox
Container(
margin: const EdgeInsets.only(top: 20),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () async {
//if button is pressed, setstate sending = true, so that we can show "sending..."
setState(() {
sending = true;
});
await sendData();
clearfields();
},
child: Text(
sending == true ? 'Sending...' : 'SEND DATA',
// "Sending",
//if sending == true then show "Sending" else show "SEND DATA";
),
// color: Colors.redAccent,
// colorBrightness: Brightness.dark,
//background of button is darker color, so set brightness to dark
)))
],
))),
);
}
void clearfields() {
namectl.clear();
desciptionctl.clear();
addrctl.clear();
image_urlctl.clear();
pricectl.clear();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439861.html
標籤:扑
上一篇:VBAADODB:替換缺失值
下一篇:GetX-中間件不觀察狀態變化?
