How to update data in mysql by flutter - mysql

I try to edit data in mysql from flutter. I send Id from page one to page two And by id I Inquire about specific data then edit it With the condition where Id=Id. Now when the application works, I can make sure Id send to php file. I try here to update field of name.
Logcat
I/flutter: tappedddd http://xxxxxxxxx/ccv.php?id=66
I can see ID is sent with the link but data now do not change in the database.I don't know what is problem. Anyone know solution for this problem?
my full code:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
import 'MyPreferences.dart';
class Update extends StatefulWidget {
var getid;
Update({Key key, this.getid}) : super(key: key);
#override
_UpdateState createState() => new _UpdateState();
}
class _UpdateState extends State<Update> {
MyPreferences _myPreferences = MyPreferences();
var getid;
var _isLoading = false;
var data;
var _username = "";
var _phone = "";
var _password = "";
var image ="";
var _phoneController = new TextEditingController();
var _firstnameController = new TextEditingController();
var _lastnameController = new TextEditingController();
Future<String> _ShowDialog(String msg) async {
return showDialog<String>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return new AlertDialog(
title: new Text('Rewind and remember'),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new Text(msg),
],
),
),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void _editData() async {
var url = "http://xxxxxxxx/ccv.php?id=${widget.getid}";
print("tappedddd $url");
var response = await http.post(url, body: {
"id": widget.getid,
// "id": _userController.text,
"name": _firstnameController.text,
// "name": _phoneController.text,
// "name": _lastnameController.text,
});
if (response.statusCode == 200) {
_ShowDialog("Updated Successfully");
} else {
_ShowDialog("Updated Failer");
}
//onEditedAccount();
//print(_adresseController.text);
}
_fetchData() async {
final url =
"http://xxxxxxxxxx/nhy.php?id=${widget.getid}";
final response = await http.get(url);
if (response.statusCode == 200) {
final map = json.decode(response.body);
final videosMap = map["result"];
setState(() {
_isLoading = true;
this.data = videosMap;
_username = data[0]['name'];
image = data[0]['image'];
print(data);
});
}
}
#override
void initState() {
super.initState();
_fetchData();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: Text("Update Profile"),
),
body: new Center(
child: data == null
? new CircularProgressIndicator()
: new ListView(
children: <Widget>[
new Padding(
padding: const EdgeInsets.fromLTRB(5, 100, 5, 5),
child: Column(
children: <Widget>[
new Padding(
padding:
const EdgeInsets.only(top: 20.0, bottom: 25.0),
child: Expanded(flex: 1,
child: Container(
child: Card(
child: new Padding(
padding: const EdgeInsets.all(5.0),
child: Image.network(
image,
width: 300,
height: 300,
fit: BoxFit.cover,
),
),
),
),
),
),
Card (
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Container(
margin: EdgeInsets.all(4),
child: TextField(
maxLength: 10,
decoration: InputDecoration(
labelText: ("name : "),
filled: true,
hintText: _username),
controller: _firstnameController,
),
),
SizedBox(
height: 5.0,
),
Container(
margin: EdgeInsets.all(4),
child: TextField(
maxLength: 8,
decoration: InputDecoration(
labelText: ("phone : "),
filled: true,
hintText: _phone),
controller: _phoneController,
),
),
SizedBox(
height: 5.0,
),
Container(
margin: EdgeInsets.all(4),
child: TextField(
maxLength: 8,
decoration: InputDecoration(
labelText: ("password : "),
filled: true,
hintText: _password),
controller: _lastnameController,
),
),
SizedBox(
height: 5.0,
),
]
)
),
SizedBox(
width: double.infinity,
child: new FlatButton(
child: const Text('Update'),color: Colors.amber,
padding: EdgeInsets.fromLTRB(100, 18, 100, 18),
onPressed: () { _editData();
},
),
),
SizedBox(
height: 10.0,
),
],
),
)
],
),
));
}
}
php file:
<?php
require_once 'connt.php';
$id=$_POST['id'];
$name =$_POST['name'];
$query="UPDATE topics SET name='$name' WHERE id='$id'";
$exeQuery = mysqli_query($con, $query) ;
if($exeQuery){
echo (json_encode(array('code' =>1, 'message' => 'Modifier avec succee')));
}else {echo(json_encode(array('code' =>2, 'message' => 'Modification Non Terminer')));
}
?>

Related

RangeError (index): Index out of range: no indices are valid: 0 - Flutter

I'm new to flutter.
When I'm trying to add list data to the widget RealAppcard of Text
the list data is '${extractRooms[0]}'
I'm getting this error
RangeError (index): Index out of range: no indices are valid: 0
but without this data added everything is working
what am I doing wrong here?
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gs/card_real_app.dart';
import 'package:gs/homescreen.dart';
import 'package:gs/network.dart';
import 'package:gs/pic_model.dart';
import 'package:gs/reusable_card.dart';
import 'package:dotted_border/dotted_border.dart';
import 'Custom_textfield.dart';
import 'order.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'ordertile.dart';
const cardinactiveColor = Color(0xFF0a1529);
const cardActivecolor = Color(0xFFffb700);
var orderData;
// List<Order> orders = <Order>[];
List<Order> OrdersItems = [];
List<dynamic> feedbacks = [];
List<dynamic> pics = [];
late final String? picData;
late final String? statusData;
List<dynamic> filteredOrdersItems = [];
List<dynamic> feedbpics = [];
// final assetController = TextEditingController();
String currentSearch = '';
// String? statusOrder;
// String? picOrder;
// String? myStr = 'shalom';
List<dynamic> extractRooms = [];
List<dynamic> extractStatus = [];
List<dynamic> extractType = [];
List<dynamic> extractMap = [];
dynamic getRooms() {
filteredOrdersItems.forEach((item) {
extractRooms.insert(0, item.rooms);
// print('${item.pic}');
});
}
dynamic getType() {
filteredOrdersItems.forEach((item) {
extractType.insert(0, item.type);
// print('${item.pic}');
});
}
dynamic getSatausData() {
filteredOrdersItems.forEach((item) {
extractStatus.insert(0, item.status);
// print('${item.pic}');
});
}
dynamic getPicData() {
filteredOrdersItems.forEach((item) {
extractMap.insert(0, item.pic);
// print('${item.pic}');
});
}
var data;
var parsedJsonText = jsonDecode(data);
class searchScreen extends StatefulWidget {
// firstScreen({Key? key}) : super(key: key);
#override
State<searchScreen> createState() => _searchScreenState();
}
class _searchScreenState extends State<searchScreen> {
#override
void initState() {
super.initState();
getOrders().then((
OrderItems,
) {
setState(() {
// this.OrderItems = OrderItems;
// filteredOrdersItems = OrderItems;
});
});
}
// void initState() {
// super.initState();
// getOrders().then((
// feedbackItems,
// ) {
// setState(() {
// // this.feedbackItems = feedbackItems;
// // this.filteredFeedbackItems = feedbackItems;
// });
// });
// }
// List<OrderModel> orders = <OrderModel>[];
Color cardColor = cardinactiveColor;
void updateColor() {
if (cardColor == cardinactiveColor) {
cardColor = cardActivecolor;
} else {
cardColor = cardinactiveColor;
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
// ignore: prefer_const_literals_to_create_immutables
Container(
height: 400,
color: Color(0xFF0a1529),
child: Column(
children: [
const Icon(
Icons.real_estate_agent_outlined,
color: Colors.white,
size: 80,
),
// data: Icons.real_estate_agent_outlined,
SizedBox(height: 5),
Text(
'ברוכים הבאים לאפליקצית חיפוש נכסים',
style: TextStyle(
fontSize: 20.0,
color: Colors.blue,
),
),
SizedBox(height: 15),
CustomTextField(
data: Icons.search,
// controller: null,
hintText: 'חיפוש נכס',
enabled: true,
// controller: assetController,
),
SizedBox(height: 15),
DottedBorder(
color: Color(0xFFffb700),
strokeWidth: 1,
child: Card(
color: Colors.transparent,
elevation: 0,
child: Container(
width: 400,
height: 140,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Padding(
padding: EdgeInsets.all(10.0),
child: Icon(
FontAwesomeIcons.crown,
// Icons.workspace_premium,
color: Color(0xFFffb700),
),
),
Padding(
padding: EdgeInsets.all(10.0),
child: Text(
'מיוחדים',
style: TextStyle(
color: Colors.white,
),
),
),
],
),
Text(
'מוזמנים להתנסות במערכת הנפלאה',
style: TextStyle(
color: Color(0xFF8d8e98),
),
),
SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
GestureDetector(
onTap: () {},
child: Card(
color: cardColor,
child: Container(
child: Row(
children: [
ButtonTheme(
minWidth: 30.0,
height: 15.0,
child: RaisedButton(
color: Colors.amber,
child: Text(
'בצעו חיפוש',
style: TextStyle(
fontSize: 20,
),
),
onPressed: () async {
feedbacks = await getOrders();
// pics = await getPic();
// feedbpics =
// pics.where((element) {
// return element.id ==
// currentSearch;
// }).toList();
// print(feedbpics);
print(feedbacks);
filteredOrdersItems =
feedbacks.where((element) {
return element.address ==
currentSearch;
}).toList();
filteredOrdersItems
.forEach((item) {
print('${item.pic}');
});
// picData = getStatus();
// statusData = getPic();
// print('pic $picData');
// print('status $statusData');
// getPic();
getPicData();
getType();
getSatausData();
getRooms();
print(
'checking ${filteredOrdersItems[0]}');
print(
'list map${filteredOrdersItems}');
print('list $extractMap');
print(extractMap[0]);
print(
'status ${extractStatus[0]}');
print(
'rooms ${extractRooms[0]}');
// print(
// 'status ${extractMapStatus}');
setState(() {});
}),
),
// Text(
// 'בדקו עכשיו',
// style: TextStyle(
// color: Colors.white,
// ),
// ),
Icon(
FontAwesomeIcons.arrowRight,
// Icons.workspace_premium,
color: Color(0xFFffb700),
),
],
),
),
),
)
],
),
],
),
),
),
),
],
),
),
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(24),
),
color: Colors.white,
elevation: 5,
child: Container(
width: 500,
height: 500,
decoration:
BoxDecoration(borderRadius: BorderRadius.circular(25)),
child: Column(
children: [
// Text('${feedbpics[0]}'),
if (filteredOrdersItems.isEmpty) ...{
Text(
"לא נמצאו תוצאות נסו שנית",
style: TextStyle(
fontSize: 20,
),
),
} else ...{
Text(
'${extractType[0]}',
style: TextStyle(
fontSize: 20,
),
),
SizedBox(height: 20),
Card(
elevation: 8,
child: Image.network(
'${extractMap[0]}',
width: 200,
height: 100,
),
),
},
// SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'כתובת מלאה',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Color(0xFFA435F0),
),
),
Text('ניקוד נכס'),
],
),
// SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
realAppCard(
text: 'חדרים',
quantity: '${extractRooms[0]}',
),
realAppCard(
text: 'גודל דירה',
quantity: '120',
),
realAppCard(
text: 'מחיר',
quantity: '1.5',
),
],
),
SizedBox(height: 10),
Card(
color: Colors.green,
elevation: 10,
child: Container(
width: 100,
height: 30,
child: Text(
'status',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 20,
),
),
),
),
SizedBox(height: 5),
Center(
child: Text(
'''
הרשות פרסמה את ממצאי התחקיר שערכה על הרג כתבת אל ג'זירה,
ממנו עולה שהחיילים ירו בה בכוונה, למרות שראו שמדובר בעיתונאית.
לטענת התובע, הקליע, שהשימוש בו לא היה חוקי
''',
textAlign: TextAlign.center,
),
),
SizedBox(height: 5),
Card(
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(10),
topRight: Radius.circular(10)),
side: BorderSide(width: 1, color: Colors.blueGrey)),
child: ListTile(
leading: Icon(Icons.message_outlined),
trailing: Text('משה כהן'),
title: Text('052-3567104'),
),
),
SizedBox(height: 5),
ElevatedButton(
onPressed: null,
child: Text('שליחת ווטסאפ'),
),
],
)),
// Center(
// child: Container(
// width: 300,
// child: TextField(
// decoration: const InputDecoration(
// border: OutlineInputBorder(), hintText: 'הקלידו הזמנה'),
// onChanged: (String newstr) {
// currentSearch = newstr;
// // print('first: ${currentSearch}');
// // print(newstr);
// // feedbackItems.forEach((element) {
// // print(element.status);
// // });
// },
// ),
// ),
// ),
// SizedBox(height: 20),
// ButtonTheme(
// minWidth: 200.0,
// height: 30.0,
// child: RaisedButton(
// color: Colors.amber,
// child: Text(
// 'בצעו חיפוש',
// style: TextStyle(
// fontSize: 20,
// ),
// ),
// onPressed: () async {
// feedbacks = await getOrders();
// print(feedbacks);
// filteredOrdersItems = feedbacks.where((element) {
// return element.id == currentSearch;
// }).toList();
// print(filteredOrdersItems);
// setState(() {});
// }),
// ),
// SizedBox(height: 10),
// ignore: sdk_version_ui_as_code
)
],
),
);
}
}
Future<List<dynamic>> getOrders() async {
String url =
'https://script.google.com/macros/s/AKfycbyT3xsBV2nrxgCotCA8-hyZ1DNTNt1ET0wuKilQZr29ac8pbpXMk7nMrCnz2_7NPW1j/exec';
var response = await http.get(Uri.parse(url));
var jsonData = convert.jsonDecode(response.body) as List;
String data = response.body;
// var parsedJson = json.decode(response.body);
// var orderModel = jsonDecode(data)[0]['pic'];
// print('this is my natun ${orderModel}');
// print('response body ${data}');
// print(jsonData);
return jsonData.map((json) => Order.fromJson(json)).toList();
// for (var order in jsonData) {
// OrdersItems.add(Order(order['id'], order['name'], order['status']));
// OrdersItems.forEach((element) {
// print("id : ${element.id}");
// });
// }
// // filteredOrdersItems =
// // OrdersItems.where((ord) => ord['id'] == 'test').toList();
// print(OrdersItems[1].id);
// print(OrdersItems);
// print(filteredOrdersItems);
// return OrdersItems;
}
// Future<List<dynamic>> getPic() async {
// String url =
// 'https://script.google.com/macros/s/AKfycbz12UnYLSmxvwGdeUH2EI7VQ8AnLMACE6IEy3bl3TcmhnyWa0Wmfxxr17swWWXCoXqd/exec';
// var response = await http.get(Uri.parse(url));
// var jsonData = convert.jsonDecode(response.body) as List;
// // print(jsonData);
// return jsonData.map((json) => Pic.fromJson(json)).toList();
// }
if you getting the error, it means one of the extractRoom throwing this is empty, so what you can do it check if the extractRoom is not empty before displaying its content.
realAppCard(
text: 'מחיר',
quantity: extractRoom.isNotEmpty ? extractRoom[0] : '0.0',
),
this will do the work

Flutter: How do i generate a json file from List using GetX package

How do i generate JSON from multiple lists using GetX package? I am using GetX package for Flutter to pass data between screens in Flutter. The list is obtained from Episode5.dart file. The list is vieewed in MyApp file which is also the place where JSON Generate Button is kept. On clicking the button, i want the json created using the data in the list above. I have the following code:
1. Episode5.dart
class Episode5 extends StatefulWidget {
#override
_Episode5State createState() => _Episode5State();
}
class _Episode5State extends State<Episode5> {
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
final form = GlobalKey<FormState>();
static var _focusNode = new FocusNode();
bool update = false;
int currentIndex = 0;
List<User> userList = [
User(name: "a", email: "a"),
User(name: "d", email: "b"),
User(name: "c", email: "c"),
];
#override
Widget build(BuildContext context) {
Widget bodyData() => DataTable(
onSelectAll: (b) {},
sortColumnIndex: 0,
sortAscending: true,
columns: <DataColumn>[
DataColumn(label: Text("Name"), tooltip: "To Display name"),
DataColumn(label: Text("Email"), tooltip: "To Display Email"),
DataColumn(label: Text("Update"), tooltip: "Update data"),
],
rows: userList
.map(
(user) => DataRow(
cells: [
DataCell(
Text(user.name),
),
DataCell(
Text(user.email),
),
DataCell(
IconButton(
onPressed: () {
currentIndex = userList.indexOf(user);
_updateTextControllers(user); // new function here
},
icon: Icon(
Icons.edit,
color: Colors.black,
),
),
),
],
),
)
.toList(),
);
return Scaffold(
appBar: AppBar(
title: Text("Data add to List Table using Form"),
),
body: Container(
child: Column(
children: <Widget>[
bodyData(),
Padding(
padding: EdgeInsets.all(10.0),
child: Form(
key: form,
child: Container(
child: Column(
children: <Widget>[
TextFormField(
controller: nameController,
focusNode: _focusNode,
keyboardType: TextInputType.text,
autocorrect: false,
maxLines: 1,
validator: (value) {
if (value.isEmpty) {
return 'This field is required';
}
return null;
},
decoration: new InputDecoration(
labelText: 'Name',
hintText: 'Name',
labelStyle: new TextStyle(
decorationStyle: TextDecorationStyle.solid),
),
),
SizedBox(
height: 10,
),
TextFormField(
controller: emailController,
keyboardType: TextInputType.text,
autocorrect: false,
maxLines: 1,
validator: (value) {
if (value.isEmpty) {
return 'This field is required';
}
return null;
},
decoration: new InputDecoration(
labelText: 'Email',
hintText: 'Email',
labelStyle: new TextStyle(
decorationStyle: TextDecorationStyle.solid)),
),
SizedBox(
height: 10,
),
Column(
children: <Widget>[
Center(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextButton(
child: Text("Add"),
onPressed: () {
form.currentState.save();
addUserToList(
nameController.text,
emailController.text,
);
},
),
TextButton(
child: Text("Update"),
onPressed: () {
form.currentState.save();
updateForm();
},
),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
ElevatedButton(
child: Text("Save and Exit"),
onPressed: () {
form.currentState.save();
addUserToList(
nameController.text,
emailController.text,
);
Navigator.pop(context, userList);
},
),
],
),
],
),
),
],
),
],
),
),
),
),
],
),
),
);
}
void updateForm() {
setState(() {
User user = User(name: nameController.text, email: emailController.text);
userList[currentIndex] = user;
});
}
void _updateTextControllers(User user) {
setState(() {
nameController.text = user.name;
emailController.text = user.email;
});
}
void addUserToList(name, email) {
setState(() {
userList.add(User(name: name, email: email));
});
}
}
1. Main.dart
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
return Scaffold(
appBar: AppBar(
title: Text("Testing List View Data From second page to first page"),
),
body: Column(
children: <Widget>[
Expanded(
child: GetBuilder<FormController>(
builder: (controller) => ListView.builder(
itemCount: controller.userList.length,
itemBuilder: (context, index) => Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Text(controller.userList[index].name),
Text(controller.userList[index].email),
],
),
),
),
),
SizedBox(
height: 10.0,
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Episode5(),
),
);
},
child: Text("Go to Form"),
),
SizedBox(
height: 10.0,
),
ElevatedButton(
onPressed: () {
generateJSON();
},
child: Text("Generate JSON"),
),
],
),
);
}
generateJSON() {
GenerateJSON generate =
GenerateJSON(controller.userList, controller.schooList);
String jsonAddress = jsonEncode(generate);
print(jsonAddress);
}
}
2. Model.dart
class User {
String name;
String email;
User({this.name, this.email});
Map toJson() => {
'name': name,
'age': email,
};
}
class GenerateJSON {
List<User> user;
List<School> school;
GenerateJSON([this.user, this.school]);
Map toJson() {
List<Map> user =
this.user != null ? this.user.map((e) => e.toJson()).toList() : null;
return {'User': user, 'School': school};
}
}
It's exist now a powerful and flexible package on pub.dev named json_bridge.
For those who want to deal with json file, checkout it here: https://pub.dev/packages/json_bridge

Variable that holds JSON data changes to null after I switch to other widgets group

I am havin this issue where I have a two step form. There is a local JSON file that I load initiating the state to use on the second step in a dropdown widget. However, when I click the continue button and switch to the second form, the variable changes to null causing to get the error "The method 'map' was called on null". I have tried loading the data in the onPressed function of the continueButton Widget, and tried to load again when creating one of the widget of the second form. But I always get this error that the map function was called on null. Help please !!!
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_signin_button/flutter_signin_button.dart';
import 'package:ofepaw/services/auth.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
class RegisterPage extends StatefulWidget {
final Function toggleView;
RegisterPage({this.toggleView});
#override
State createState() => RegisterPageState();
}
class RegisterPageState extends State<RegisterPage> {
final AuthService _auth = AuthService();
// store the step we are in
int step = 1;
// Text Field
String emailOrPhone = "";
String pass = "";
String verifyPass = "";
String firstName = "";
String lastName = "";
String department = "";
String arrondissement = "";
String commune = "";
// variable for errors
String error = "";
// array containing the forms
var form1;
var form2;
// Controllers for the Textfields
final _emailOrPhoneController = TextEditingController();
final _passwordController = TextEditingController();
final _verifyPassController = TextEditingController();
final _firstNameController = TextEditingController();
final _lastNameController = TextEditingController();
//final _departmentController = TextEditingController();
//load the geographic division of Haiti json file
var division;
// get the locations data
Future<void> loadDivision() async {
String jsonString = await rootBundle
.loadString('assets/haiti_administrative_district.json');
Map<String, dynamic> map = json.decode(jsonString);
List<dynamic> data = map["departments"];
setState(() {
division = data;
});
}
// function to register user in ofepaw database
Future registerUser(
String id, String fname, String lname, String department) async {
final String url = "url go here";
final response = await http.post(url, body: {
"id": id,
"fname": fname,
"lname": lname,
"department": department
});
if (response.statusCode == 201) {
print("This is the response from the server");
print(response.body);
print("Response passed");
} else {
print("Error occured");
}
print(" The response is : ");
print(response.body.toString());
}
//functions for switching forms
getForm(int form) {
if (form == 1) {
return form1;
} else if (form == 2) {
return form2;
}
}
#override
void initState() {
super.initState();
loadDivision();
print(division);
form1 = <Widget>[
firstForm(),
Text("Or Sign Up with social media"),
SizedBox(
height: 20,
),
socialMediaButtons(),
SizedBox(
height: 50,
),
InkWell(
onTap: () {
widget.toggleView();
},
child: Text("Have an account? Login"))
];
form2 = <Widget>[
secondForm(),
InkWell(
//back button
onTap: () => setState(() => step = 1),
child: Text("Back"))
];
}
// dispose all controllers
// dispose of all TextEditingControllers
#override
void dispose() {
_emailOrPhoneController.dispose();
_passwordController.dispose();
_verifyPassController.dispose();
_firstNameController.dispose();
_lastNameController.dispose();
//_departmentController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Material(
child: Expanded(
child: Stack(
children: <Widget>[
// banner with picture
Positioned(
child: banner(),
),
// Login Elements Container
Positioned(
child: Container(
margin: EdgeInsets.only(top: 300.0),
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 5,
blurRadius: 20,
offset: Offset(0, 0))
],
borderRadius: BorderRadius.only(
topRight: Radius.circular(50),
topLeft: Radius.circular(50))),
child: Center(
child: Column(
children: getForm(step),
),
),
),
)
],
),
),
);
}
Widget banner() {
return Container(
height: 350,
decoration: BoxDecoration(color: Colors.white),
child: Center(
child: Image.network(
"https://image.freepik.com/free-vector/man-using-his-phone-instead-working_23-2148501890.jpg"),
),
);
}
Widget emailField() {
return TextFormField(
controller: _emailOrPhoneController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintText: "Email or Phone Number",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => emailOrPhone = val);
},
);
}
Widget firstNameField() {
return TextFormField(
controller: _firstNameController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintText: "First Name",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => firstName = val);
},
);
}
Widget lastNameField() {
return TextFormField(
controller: _lastNameController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintText: "Last Name",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => lastName = val);
},
);
}
Widget departmentField() {
return DropdownButtonFormField(
items: division.map<DropdownMenuItem<String>>((value) {
return DropdownMenuItem<String>(
value: value["name"],
child: Text(value["name"]),
);
}).toList(),
hint: Text("Choose the department"),
onChanged: (value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
);
}
Widget arrondissementField() {
return DropdownButtonFormField(
items: [
DropdownMenuItem(
child: Text("Delmas"),
value: 1,
),
DropdownMenuItem(
child: Text("Petion-Ville"),
value: 2,
)
],
hint: Text("Choose the department"),
onChanged: (int value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)));
}
Widget communeField() {
return DropdownButtonFormField(
items: [
DropdownMenuItem(
child: Text("Delmas"),
value: 1,
),
DropdownMenuItem(
child: Text("Petion-Ville"),
value: 2,
)
],
hint: Text("Choose the department"),
onChanged: (int value) {
setState(() {});
},
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 10, left: 20, right: 20),
border: InputBorder.none,
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)));
}
Widget passwordField() {
return TextFormField(
controller: _passwordController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 5, left: 20, right: 20),
border: InputBorder.none,
hintText: "Password",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => pass = val);
});
}
Widget verifyPasswordField() {
return TextFormField(
controller: _verifyPassController,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(bottom: 5, left: 20, right: 20),
border: InputBorder.none,
hintText: "Reenter Password",
hintStyle: TextStyle(color: Colors.grey[400], fontSize: 15)),
onChanged: (val) {
setState(() => verifyPass = val);
});
}
Widget socialMediaButtons() {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SignInButton(Buttons.Facebook,
mini: true, onPressed: () => print("Facebook Sign in ...")),
SignInButton(Buttons.Google,
//mini: true,
onPressed: () => print("Google Sign in ..."))
],
);
}
Widget continueButton() {
return ButtonTheme(
minWidth: 185.0,
height: 48.0,
child: RaisedButton(
color: Colors.black,
textColor: Colors.white,
child: Text("continue"),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50.0)),
onPressed: () {
print(division);
setState(() {
step = 2;
});
},
));
}
Widget signUpButton() {
return ButtonTheme(
minWidth: 185.0,
height: 48.0,
child: RaisedButton(
color: Colors.black,
textColor: Colors.white,
child: Text("Sign Up"),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50.0)),
onPressed: () async {
dynamic result =
await _auth.registerWithEmailAndPassword(emailOrPhone, pass);
if (result == null) {
setState(() => error = "Email or Password incorrect");
} else {
// Register user ID in the server database
registerUser(result.user.uid, firstName, lastName, department);
}
},
));
}
Widget emailPassField() {
return Container(
// Form input field
margin: EdgeInsets.only(top: 40.0),
width: 320.0,
height: 180.0,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 0.2,
blurRadius: 5,
offset: Offset(0, 0))
],
borderRadius: BorderRadius.circular(20)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
emailField(),
Divider(),
passwordField(),
Divider(),
verifyPasswordField()
],
),
);
}
Widget personalInfoField() {
return Container(
// Form input field
margin: EdgeInsets.only(top: 40.0),
width: 320.0,
height: 310.0,
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.2),
spreadRadius: 0.2,
blurRadius: 5,
offset: Offset(0, 0))
],
borderRadius: BorderRadius.circular(20)),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
firstNameField(),
Divider(),
lastNameField(),
Divider(),
departmentField(),
Divider(),
arrondissementField(),
Divider(),
communeField()
],
),
);
}
Widget firstForm() {
return Column(
children: <Widget>[
emailPassField(),
SizedBox(
height: 50,
),
continueButton(),
SizedBox(
height: 50,
),
],
);
}
Widget secondForm() {
return Column(
children: <Widget>[
personalInfoField(),
SizedBox(
height: 40,
),
signUpButton(),
SizedBox(
height: 40,
),
],
);
}
}
The root of your problem starts here String jsonString = await rootBundle.loadString('assets/haiti_administrative_district.json');
Are you sure your project can recognize thise: 'assets/haiti_administrative_district.json'? Have you added it to your assests in pubspec.yaml?
Because this is line is returning null, everything downward will b e returning null, including the error you are reciving.
Future<void> loadDivision() async {
String jsonString = await rootBundle
.loadString('assets/haiti_administrative_district.json');
Map<String, dynamic> map = json.decode(jsonString);
List<dynamic> data = map["departments"];
setState(() {
division = data;
});
}
Here, first make sure data is getting loaded in jsonString.
Second, make sure json.decode(jsonString) is returning json object and not array of json objects.
If it is returning array of json objects, store it in a List<Map>.
Then make a list like this:
List<Map> maps = json.decode(jsonString);
List data=new List();
maps.forEach((element)=>data.add(element['departments']));

Displaying complex json in FormBuilderRadioGroup in flutter_form_builder flutter

I'm having trouble displaying 'option' and getting (print in terminal) the 'id' of the chosen option.
How can I retrieve the json as map and use it effectively in flutter_form_builder?
Here is the json object:
{
id: 7,
poll: What is the capital of Egypt?,
created_at: 2020-10-22 10:53:41,
votes_count: 4,
likes_count: 0,
options: [
{
id: 20,
option: Tunis,
pollId: 7,
votes_count: 1
}, {
id: 21,
option: Cairo,
pollId: 7,
votes_count: 3
}, {
id: 22,
option: New York,
pollId: 7,
votes_count: 0
}],
user_name: salem,
user_image: null,
topics: []
}
Here is my poll_details page:
import 'package:flutter/material.dart';
import 'package:circular_profile_avatar/circular_profile_avatar.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:like_button/like_button.dart';
import '../services/poll_services.dart';
import '../widgets/loading_widget.dart';
class PollDetails extends StatefulWidget {
final id;
PollDetails({this.id});
#override
_PollDetailsState createState() => _PollDetailsState(id);
}
class _PollDetailsState extends State<PollDetails> {
var id;
_PollDetailsState(this.id);
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
#override
void initState() {
super.initState();
optionsList.clear();
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(title: Text("Details")),
body: FutureBuilder(
future: singlePoll(id),
builder: (context, snapshot) {
if(snapshot.hasData){
return ListView(
padding: EdgeInsets.fromLTRB(18, 40, 18, 0),
children: [
Padding(
padding: EdgeInsets.only(bottom: 20),
child: Container(
padding: EdgeInsets.fromLTRB(10, 40, 0, 40),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10.0),
border: Border.all(
color: Theme.of(context).primaryColor,
width: 5.0,
style: BorderStyle.solid
)
),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
if(imgPath(snapshot.data) == null) CircleAvatar(radius: 35,child: Image.asset('images/avatar.png'))
else CircularProfileAvatar(
imgPath(snapshot.data),
radius: 35,
borderWidth: 3.0,
borderColor: Colors.white,
backgroundColor: Colors.transparent,
foregroundColor: Colors.transparent,
errorWidget: (context, url, error) => Container(child: Icon(Icons.error)),
placeHolder: (context, url) => Container(
width: 50,
height: 50,
child: Text("Loading image..."),
)
),
SizedBox(width: 10.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
userName(snapshot.data),
style: TextStyle(fontSize: 20)
),
Flexible(
fit: FlexFit.loose,
child: Text(
votesCount(snapshot.data).toString()+" participants to this poll",
style: TextStyle(fontSize: 13)
)
)
]
)
)
]
)
)
),
///////////////////////////////// POLLS //////////////////////////////////////////////
FormBuilder(
key: _fbKey,
autovalidateMode: AutovalidateMode.always,
child: FormBuilderRadioGroup(
attribute: 'options',
decoration: InputDecoration(labelText: 'Choose only one:'),
validators: [FormBuilderValidators.required()],
orientation: GroupedRadioOrientation.vertical,
options: [
for (var i in optionsList) i['option'].toString()
]
.map((option) => FormBuilderFieldOption(value: option))
.toList(growable: false),
)
),
RaisedButton(
child: Text("Submit"),
onPressed: () async{
_fbKey.currentState.save();
if (_fbKey.currentState.validate()) {
// Loading().show(context);
var option = _fbKey.currentState.value['options'];
print(option);
// var resp = await createPoll(question, tagS, choiceS);
// if(resp['status'] == "success"){
// Navigator.pop(context); //pop dialog
// } else {
// Navigator.pop(context); //pop dialog
// }
}
}
),
//////////////////////////// Like Button ///////////////////////////////
Row(
children: [
LikeButton(
size: 40,
circleColor:
CircleColor(start: Colors.red, end: Colors.red),
bubblesColor: BubblesColor(
dotPrimaryColor: Colors.red,
dotSecondaryColor: Colors.red,
),
likeBuilder: (bool isLiked) {
return Icon(
Icons.favorite,
color: isLiked ? Colors.red : Colors.grey,
size: 40,
);
},
likeCount: likes(snapshot.data),
countBuilder: (int count, bool isLiked, String text) {
var color = isLiked ? Colors.red : Colors.grey;
Widget result;
if (count == 0) {
result = Text(
"0",
style: TextStyle(color: color),
);
} else
result = Text(
text,
style: TextStyle(color: color),
);
return result;
}
),
Expanded(child: Text(" have liked this. Show some love, too!"))
]
),
Column(
children: [
// optionsList.forEach((element) => Text('option'))
for (var i in optionsList) Text(i['option'].toString())
]
),
RaisedButton(
child: Text("data"),
onPressed: (){singlePoll(id);}
)
]
);
}else {
return Center(child: CircularProgressIndicator());
}
}
)
)
);
}
}
And here is the request I use to get the response:
Future singlePoll(int id) async {
String url = baseUrl+"poll/get";
var stringID = id.toString();
var token = await storage.read(key: "jwt");
try{
final response = await http.post(
url,
headers: {'Accept':'application/json', 'Authorization':token},
body: {'pollId':stringID}
);
var dataToJson = jsonDecode(response.body);
for (var option in dataToJson['options']){
var optionID = option['id'];
var optionTitle = option['option'].toString();
var votesCount = option['votes_count'];
optionsList.add(option);
}
print(dataToJson);
return dataToJson;
} catch (e){
print('error caught: $e');
}
}
As you can see, I used a work around to get the list and display it.
Any suggestion is valuable.
Thanks in advance...
You need to use setState() in here:
setState() {
var optionID = option['id'];
var optionTitle = option['option'].toString();
var votesCount = option['votes_count'];
optionsList.add(option);
}
You can read more from the official document and look at here.

How do you set TextField text to text received from JSON file? (Flutter)

I am pretty new to flutter and I was wondering how I could set the the TextField text using a TextEditController (named crText) to a text received from a JSON file. The text from the JSON file is stored in chemText which is a String. The getData method, which has all the querying functions is called during an onPressed method in the "Search" icon. The text in the TextField is desired to be changed using "controller: " which is set to crText. The goal here is to set crText to chemText (which holds the text from queryData variable (json.decode(queryParams)). The "controller: " can be found at the very end of the code segment.
import 'dart:ffi';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'dart:convert';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class myClass extends StatelessWidget{
var crText = TextEditingController();
String chemText;
var queryParameters = {
"ID" : "nfuiwnfuiwnfuinfuwnfuinw" //just one of the hashes (example)
};
Future<String> getData() async{
var uri =
Uri.https('www.myUrl.com', 'api/parameters', queryParameters);
Icon searchIcon = Icon(Icons.search);
var objMapUrl = "https://myUrl.com";
Map data;
Map queryData;
http.Response response = await http.get(
Uri.encodeFull(objMapUrl),
headers: {
"key" : "ifhfi2jfowjefounf893f"
}
);
var queryParams = await http.get(uri, headers: {
"key" : "ifhfi2jfowjefounf893f"
});
//data = json.decode(response.body);
//print(data["hashes"]);
// print( data["names"]);
// print(data); //prints hashes
//query parameters
queryData = json.decode(queryParams.body);
//print(queryData);
chemText = queryData.toString();
print(chemText);
return chemText;
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0.0,
automaticallyImplyLeading: false,
title: Container(
margin: EdgeInsets.symmetric(horizontal: 1.0, vertical: 8.0),
decoration: BoxDecoration(
color: Colors.lightBlueAccent,
borderRadius: BorderRadius.all(Radius.circular(12.0)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
flex: 1,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 5.0),
child: TextFormField(
textInputAction: TextInputAction.done,
onFieldSubmitted: (term){
getData();
},
cursorColor: Colors.white,
decoration: InputDecoration(
border: InputBorder.none,
hintText: "Enter Name",
hintStyle: TextStyle(color: Colors.white),
),
),
),
),
Expanded(
flex: 0,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 0.0),
child: Row(
children: <Widget>[
IconButton(
onPressed: getData,
icon: Icon(Icons.search, color: Colors.white),
),
],
),
),
),
],
),
),
),
body: new Container(
padding: new EdgeInsets.fromLTRB(25.0, 200.0, 25.0, 0.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment. center,
children: <Widget>[
new TextField(
decoration: new InputDecoration(
border: const OutlineInputBorder(
borderSide: const BorderSide(
color: Colors.blueGrey, width: 2.0
)
)
),
//textfield text needs to change to the text recieved from json.decode(queryParams.body) or chemText
controller: crText,
maxLines: 20,
)
],
),
),
);
}
}
add
setState(() {
crText.text = chemText
});
somewhere. Maybe after parsing your json.