I Created this form to submit the data to API.
But something is wrong there is an error. i declared the variable nullable still this error came to me.
I don't know what's the problem.
Note: I don't only want to solve this error but I want to understand what I missed.
Could you please explain??
import 'dart:async'; import 'dart:convert';
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();
}
}
CodePudding user response:
sending
can be null, and Dart doesn't see null as a falsy value able to be used inside a ternary. You can rewrite your ternary like this if you're sure that sending
isn't null at this point:
sending! ? "Sending..." : "SEND DATA",
Or, if you're not sure whether it's null or not.
sending == true ? "Sending..." : "SEND DATA",
CodePudding user response:
In your code error, sending, success, msg
all these variables are optional means you may get value or null as a value.
Dart doesn't consider the null value as false. You need to give true are false values only.
Updated Code:
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();
}
}