Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.93 KB | None | 0 0
  1. import 'package:flutter/material.dart';
  2. import 'dart:convert';
  3. import 'dart:async';
  4. import 'package:http/http.dart' as http;
  5. import 'package:requests/requests.dart';
  6. import 'package:toast/toast.dart';
  7. import 'package:validate/validate.dart';
  8. // import 'package:contactapp/widgets/Counter.dart';
  9.  
  10. final String baseUrl = "http://api.iamhermawan.com/";
  11. final String apiKey = "?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsdW1lbi1qd3QiLCJzdWIiOjEzLCJpYXQiOjE1NzQxNDU0NTd9.7ZRcFREKY65HUHYYwobW_9hKhFHuLuv0NRhQpdPx9lA";
  12.  
  13. class Contact extends StatefulWidget {
  14. _ContactState createState() => _ContactState();
  15. }
  16.  
  17. class _ContactState extends State < Contact > {
  18. final String uri = baseUrl + "users" + apiKey;
  19. var listOfUsers = new List < Contacts > ();
  20.  
  21. Future < List < Contacts >> _fetchContacts() async {
  22. var response = await http.get(uri);
  23.  
  24. if (response.statusCode == 200) {
  25. final result = json.decode(response.body);
  26. Iterable list = result["data"];
  27. listOfUsers = list.map((model) => Contacts.fromJson(model)).toList();
  28.  
  29. return listOfUsers;
  30. } else {
  31. throw Exception('Failed to load internet');
  32. }
  33. }
  34.  
  35. void _showDialog() {
  36. // flutter defined function
  37. showDialog(
  38. context: context,
  39. builder: (BuildContext context) {
  40. // return object of type Dialog
  41. return AlertDialog(
  42.  
  43. title: new Text("Delete Contact"),
  44. content: new Text("Are you sure delete this contact?"),
  45. actions: < Widget > [
  46. // usually buttons at the bottom of the dialog
  47. new FlatButton(
  48. child: new Text("Yes"),
  49. onPressed: () {
  50. submitDelete();
  51. Navigator.of(context).pop();
  52. },
  53. ),
  54. new FlatButton(
  55. child: new Text("No"),
  56. onPressed: () {
  57. Navigator.of(context).pop();
  58. },
  59. ),
  60. ],
  61. );
  62. },
  63. );
  64. }
  65.  
  66. void submitDelete() async {
  67. var url = baseUrl + "users/delete" + apiKey;
  68. var response = await Requests.post(url, body: {
  69. "email": _deleteEmailState,
  70. }, bodyEncoding: RequestBodyEncoding.FormURLEncoded);
  71.  
  72. if (response.statusCode == 200) {
  73. var parsedJson = json.decode(response.content());
  74. if (parsedJson['result'] == 1) {
  75. showToast(parsedJson['message'], gravity: Toast.TOP);
  76. _fetchContacts();
  77. } else {
  78. showToast(parsedJson['reason'], duration: Toast.LENGTH_LONG, gravity: Toast.TOP);
  79. }
  80. } else {
  81. showToast("Network failure", gravity: Toast.TOP);
  82. }
  83. }
  84.  
  85. void showToast(String msg, {
  86. int duration,
  87. int gravity
  88. }) {
  89. Toast.show(msg, context, duration: duration, gravity: gravity);
  90. }
  91.  
  92. // int _deleteState = 0;
  93. String _deleteEmailState = "";
  94. @override
  95. Widget build(BuildContext context) {
  96.  
  97. return Scaffold(
  98. appBar: AppBar(
  99. title: Text('Contact'),
  100. ),
  101. body: FutureBuilder < List < Contacts >> (
  102. future: _fetchContacts(),
  103. builder: (context, snapshot) {
  104. if (!snapshot.hasData) return Center(child: CircularProgressIndicator());
  105.  
  106. return ListView.builder(
  107. itemCount: snapshot.data.length,
  108. itemBuilder: (context, index) {
  109.  
  110. return Card( // <-- Card
  111. child: ListTile(
  112. onLongPress: () {
  113. _showDialog();
  114. setState(() {
  115. // _deleteState = snapshot.data[index].id;
  116. _deleteEmailState = snapshot.data[index].email;
  117. });
  118. },
  119. onTap: () {
  120. Navigator.push(
  121. context,
  122. MaterialPageRoute(builder: (context) => AddContact()),
  123. );
  124. },
  125. title: Text(snapshot.data[index].name),
  126. subtitle: Text(snapshot.data[index].email),
  127. leading: CircleAvatar(
  128. backgroundColor: Colors.red,
  129. child: Text(snapshot.data[index].name[0],
  130. style: TextStyle(
  131. fontSize: 18.0,
  132. color: Colors.white,
  133. )),
  134. ),
  135. ),
  136. );
  137. },
  138. // children: snapshot.data
  139. // .map((contact) => ListTile(
  140. // title: Text(contact.name),
  141. // subtitle: Text(contact.email),
  142. // leading: CircleAvatar(
  143. // backgroundColor: Colors.red,
  144. // child: Text(contact.name[0],
  145. // style: TextStyle(
  146. // fontSize: 18.0,
  147. // color: Colors.white,
  148. // )),
  149. // ),
  150. // ))
  151. // .toList(),
  152. );
  153. },
  154. ),
  155. floatingActionButton: Padding(
  156. padding: const EdgeInsets.only(bottom: 20.0),
  157. child: FloatingActionButton(
  158. onPressed: () {
  159. Navigator.push(
  160. context,
  161. MaterialPageRoute(builder: (context) => AddContact()),
  162. );
  163. },
  164. tooltip: 'Add Contact',
  165. child: Icon(Icons.add),
  166. ),
  167. ),
  168. );
  169. }
  170. }
  171.  
  172. class Contacts {
  173. int id;
  174. String name;
  175. String email;
  176.  
  177. Contacts({
  178. this.id,
  179. this.name,
  180. this.email,
  181. });
  182.  
  183. factory Contacts.fromJson(Map < String, dynamic > json) {
  184. return Contacts(
  185. id: json['id'],
  186. name: json['name'],
  187. email: json['email'],
  188. );
  189. }
  190. }
  191.  
  192. class _FormData {
  193. String name = '';
  194. String email = '';
  195. String password = '';
  196. String repassword = '';
  197. }
  198.  
  199. class AddContact extends StatefulWidget {
  200. @override
  201. _AddContactState createState() => _AddContactState();
  202. }
  203.  
  204. class _AddContactState extends State < AddContact > {
  205. final GlobalKey < FormState > _formKey = new GlobalKey < FormState > ();
  206. final passtxt = TextEditingController();
  207.  
  208. _FormData _data = new _FormData();
  209.  
  210. String _validateName(String value) {
  211. if (value == "") {
  212. return 'The Name cant empty.';
  213. }
  214.  
  215. if (value.length < 3) {
  216. return 'The Name must be at least 8 characters.';
  217. }
  218.  
  219. return null;
  220. }
  221.  
  222. String _validateEmail(String value) {
  223. // If empty value, the isEmail function throw a error.
  224. // So I changed this function with try and catch.
  225. try {
  226. Validate.isEmail(value);
  227. } catch (e) {
  228. return 'The E-mail Address must be a valid email address.';
  229. }
  230.  
  231. return null;
  232. }
  233.  
  234. String _validatePassword(String value) {
  235. if (value == "") {
  236. return 'Password field cant empty';
  237. }
  238.  
  239. if (value.length < 8) {
  240. return 'The Password must be at least 8 characters.';
  241. }
  242.  
  243. return null;
  244. }
  245.  
  246. String _validateRePassword(String value) {
  247. if (passtxt.text == "" || passtxt.text == null) {
  248. return 'Password field cant empty';
  249. }
  250.  
  251. if (value != passtxt.text) {
  252. return 'Password didnt match';
  253. }
  254.  
  255. return null;
  256. }
  257.  
  258. void submit() async {
  259. // First validate form.
  260. if (this._formKey.currentState.validate()) {
  261. _formKey.currentState.save(); // Save our form now.
  262.  
  263. // print('Printing the login data.');
  264. // print('Name: ${_data.name}');
  265. // print('Email: ${_data.email}');
  266. // print('Password: ${_data.password}');
  267. // print('Re Password: ${_data.repassword}');
  268. var url = baseUrl + "users" + apiKey;
  269. var response = await http.post(url, body: {
  270. 'name': _data.name,
  271. 'email': _data.email,
  272. 'password': _data.password,
  273. 'password_confirmation': _data.repassword,
  274. });
  275.  
  276. if (response.statusCode == 200) {
  277. var parsedJson = json.decode(response.body);
  278. if (parsedJson['result'] == 1) {
  279. showToast(parsedJson['message'], gravity: Toast.TOP);
  280. } else {
  281. showToast(parsedJson['reason'][0], duration: Toast.LENGTH_LONG, gravity: Toast.TOP);
  282. }
  283. } else {
  284. showToast("Network failure", gravity: Toast.TOP);
  285. }
  286. }
  287. }
  288.  
  289. void showToast(String msg, {
  290. int duration,
  291. int gravity
  292. }) {
  293. Toast.show(msg, context, duration: duration, gravity: gravity);
  294. }
  295.  
  296. @override
  297. Widget build(BuildContext context) {
  298. final Size screenSize = MediaQuery.of(context).size;
  299. return Scaffold(
  300. appBar: AppBar(
  301. title: Text("Add Contact"),
  302. ),
  303. body: new Container(
  304. padding: new EdgeInsets.all(20.0),
  305. child: new Form(
  306. key: this._formKey,
  307. child: new ListView(
  308. children: < Widget > [
  309. new TextFormField(
  310. keyboardType: TextInputType.text,
  311. decoration: new InputDecoration(
  312. hintText: 'John Doe',
  313. labelText: 'Your Name'
  314. ),
  315. validator: this._validateName,
  316. onSaved: (String value) {
  317. this._data.name = value;
  318. }
  319. ),
  320. new TextFormField(
  321. keyboardType: TextInputType.emailAddress, // Use email input type for emails.
  322. decoration: new InputDecoration(
  323. hintText: 'you@example.com',
  324. labelText: 'E-mail Address'
  325. ),
  326. validator: this._validateEmail,
  327. onSaved: (String value) {
  328. this._data.email = value;
  329. }
  330. ),
  331. new TextFormField(
  332. controller: passtxt,
  333. obscureText: true, // Use secure text for passwords.
  334. decoration: new InputDecoration(
  335. hintText: 'Password',
  336. labelText: 'Enter your password'
  337. ),
  338. validator: this._validatePassword,
  339. onSaved: (String value) {
  340. this._data.password = value;
  341. }
  342. ),
  343. new TextFormField(
  344. obscureText: true, // Use secure text for passwords.
  345. decoration: new InputDecoration(
  346. hintText: 'Re Password',
  347. labelText: 'Re Enter your password'
  348. ),
  349. validator: this._validateRePassword,
  350. onSaved: (String value) {
  351. this._data.repassword = value;
  352. }
  353. ),
  354. new Container(
  355. width: screenSize.width,
  356. child: new RaisedButton(
  357. child: new Text(
  358. 'Submit',
  359. style: new TextStyle(
  360. color: Colors.white
  361. ),
  362. ),
  363. onPressed: this.submit,
  364. color: Colors.blue,
  365. ),
  366. margin: new EdgeInsets.only(
  367. top: 20.0
  368. ),
  369. )
  370. ],
  371. ),
  372. )
  373. ),
  374. );
  375. }
  376. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement