Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/material.dart';
- import 'dart:convert';
- import 'dart:async';
- import 'package:http/http.dart' as http;
- import 'package:requests/requests.dart';
- import 'package:toast/toast.dart';
- import 'package:validate/validate.dart';
- // import 'package:contactapp/widgets/Counter.dart';
- final String baseUrl = "http://api.iamhermawan.com/";
- final String apiKey = "?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsdW1lbi1qd3QiLCJzdWIiOjEzLCJpYXQiOjE1NzQxNDU0NTd9.7ZRcFREKY65HUHYYwobW_9hKhFHuLuv0NRhQpdPx9lA";
- class Contact extends StatefulWidget {
- _ContactState createState() => _ContactState();
- }
- class _ContactState extends State < Contact > {
- final String uri = baseUrl + "users" + apiKey;
- var listOfUsers = new List < Contacts > ();
- Future < List < Contacts >> _fetchContacts() async {
- var response = await http.get(uri);
- if (response.statusCode == 200) {
- final result = json.decode(response.body);
- Iterable list = result["data"];
- listOfUsers = list.map((model) => Contacts.fromJson(model)).toList();
- return listOfUsers;
- } else {
- throw Exception('Failed to load internet');
- }
- }
- void _showDialog() {
- // flutter defined function
- showDialog(
- context: context,
- builder: (BuildContext context) {
- // return object of type Dialog
- return AlertDialog(
- title: new Text("Delete Contact"),
- content: new Text("Are you sure delete this contact?"),
- actions: < Widget > [
- // usually buttons at the bottom of the dialog
- new FlatButton(
- child: new Text("Yes"),
- onPressed: () {
- submitDelete();
- Navigator.of(context).pop();
- },
- ),
- new FlatButton(
- child: new Text("No"),
- onPressed: () {
- Navigator.of(context).pop();
- },
- ),
- ],
- );
- },
- );
- }
- void submitDelete() async {
- var url = baseUrl + "users/delete" + apiKey;
- var response = await Requests.post(url, body: {
- "email": _deleteEmailState,
- }, bodyEncoding: RequestBodyEncoding.FormURLEncoded);
- if (response.statusCode == 200) {
- var parsedJson = json.decode(response.content());
- if (parsedJson['result'] == 1) {
- showToast(parsedJson['message'], gravity: Toast.TOP);
- _fetchContacts();
- } else {
- showToast(parsedJson['reason'], duration: Toast.LENGTH_LONG, gravity: Toast.TOP);
- }
- } else {
- showToast("Network failure", gravity: Toast.TOP);
- }
- }
- void showToast(String msg, {
- int duration,
- int gravity
- }) {
- Toast.show(msg, context, duration: duration, gravity: gravity);
- }
- // int _deleteState = 0;
- String _deleteEmailState = "";
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text('Contact'),
- ),
- body: FutureBuilder < List < Contacts >> (
- future: _fetchContacts(),
- builder: (context, snapshot) {
- if (!snapshot.hasData) return Center(child: CircularProgressIndicator());
- return ListView.builder(
- itemCount: snapshot.data.length,
- itemBuilder: (context, index) {
- return Card( // <-- Card
- child: ListTile(
- onLongPress: () {
- _showDialog();
- setState(() {
- // _deleteState = snapshot.data[index].id;
- _deleteEmailState = snapshot.data[index].email;
- });
- },
- onTap: () {
- Navigator.push(
- context,
- MaterialPageRoute(builder: (context) => AddContact()),
- );
- },
- title: Text(snapshot.data[index].name),
- subtitle: Text(snapshot.data[index].email),
- leading: CircleAvatar(
- backgroundColor: Colors.red,
- child: Text(snapshot.data[index].name[0],
- style: TextStyle(
- fontSize: 18.0,
- color: Colors.white,
- )),
- ),
- ),
- );
- },
- // children: snapshot.data
- // .map((contact) => ListTile(
- // title: Text(contact.name),
- // subtitle: Text(contact.email),
- // leading: CircleAvatar(
- // backgroundColor: Colors.red,
- // child: Text(contact.name[0],
- // style: TextStyle(
- // fontSize: 18.0,
- // color: Colors.white,
- // )),
- // ),
- // ))
- // .toList(),
- );
- },
- ),
- floatingActionButton: Padding(
- padding: const EdgeInsets.only(bottom: 20.0),
- child: FloatingActionButton(
- onPressed: () {
- Navigator.push(
- context,
- MaterialPageRoute(builder: (context) => AddContact()),
- );
- },
- tooltip: 'Add Contact',
- child: Icon(Icons.add),
- ),
- ),
- );
- }
- }
- class Contacts {
- int id;
- String name;
- String email;
- Contacts({
- this.id,
- this.name,
- this.email,
- });
- factory Contacts.fromJson(Map < String, dynamic > json) {
- return Contacts(
- id: json['id'],
- name: json['name'],
- email: json['email'],
- );
- }
- }
- class _FormData {
- String name = '';
- String email = '';
- String password = '';
- String repassword = '';
- }
- class AddContact extends StatefulWidget {
- @override
- _AddContactState createState() => _AddContactState();
- }
- class _AddContactState extends State < AddContact > {
- final GlobalKey < FormState > _formKey = new GlobalKey < FormState > ();
- final passtxt = TextEditingController();
- _FormData _data = new _FormData();
- String _validateName(String value) {
- if (value == "") {
- return 'The Name cant empty.';
- }
- if (value.length < 3) {
- return 'The Name must be at least 8 characters.';
- }
- return null;
- }
- String _validateEmail(String value) {
- // If empty value, the isEmail function throw a error.
- // So I changed this function with try and catch.
- try {
- Validate.isEmail(value);
- } catch (e) {
- return 'The E-mail Address must be a valid email address.';
- }
- return null;
- }
- String _validatePassword(String value) {
- if (value == "") {
- return 'Password field cant empty';
- }
- if (value.length < 8) {
- return 'The Password must be at least 8 characters.';
- }
- return null;
- }
- String _validateRePassword(String value) {
- if (passtxt.text == "" || passtxt.text == null) {
- return 'Password field cant empty';
- }
- if (value != passtxt.text) {
- return 'Password didnt match';
- }
- return null;
- }
- void submit() async {
- // First validate form.
- if (this._formKey.currentState.validate()) {
- _formKey.currentState.save(); // Save our form now.
- // print('Printing the login data.');
- // print('Name: ${_data.name}');
- // print('Email: ${_data.email}');
- // print('Password: ${_data.password}');
- // print('Re Password: ${_data.repassword}');
- var url = baseUrl + "users" + apiKey;
- var response = await http.post(url, body: {
- 'name': _data.name,
- 'email': _data.email,
- 'password': _data.password,
- 'password_confirmation': _data.repassword,
- });
- if (response.statusCode == 200) {
- var parsedJson = json.decode(response.body);
- if (parsedJson['result'] == 1) {
- showToast(parsedJson['message'], gravity: Toast.TOP);
- } else {
- showToast(parsedJson['reason'][0], duration: Toast.LENGTH_LONG, gravity: Toast.TOP);
- }
- } else {
- showToast("Network failure", gravity: Toast.TOP);
- }
- }
- }
- void showToast(String msg, {
- int duration,
- int gravity
- }) {
- Toast.show(msg, context, duration: duration, gravity: gravity);
- }
- @override
- Widget build(BuildContext context) {
- final Size screenSize = MediaQuery.of(context).size;
- return Scaffold(
- appBar: AppBar(
- title: Text("Add Contact"),
- ),
- body: new Container(
- padding: new EdgeInsets.all(20.0),
- child: new Form(
- key: this._formKey,
- child: new ListView(
- children: < Widget > [
- new TextFormField(
- keyboardType: TextInputType.text,
- decoration: new InputDecoration(
- hintText: 'John Doe',
- labelText: 'Your Name'
- ),
- validator: this._validateName,
- onSaved: (String value) {
- this._data.name = value;
- }
- ),
- new TextFormField(
- keyboardType: TextInputType.emailAddress, // Use email input type for emails.
- decoration: new InputDecoration(
- hintText: 'you@example.com',
- labelText: 'E-mail Address'
- ),
- validator: this._validateEmail,
- onSaved: (String value) {
- this._data.email = value;
- }
- ),
- new TextFormField(
- controller: passtxt,
- obscureText: true, // Use secure text for passwords.
- decoration: new InputDecoration(
- hintText: 'Password',
- labelText: 'Enter your password'
- ),
- validator: this._validatePassword,
- onSaved: (String value) {
- this._data.password = value;
- }
- ),
- new TextFormField(
- obscureText: true, // Use secure text for passwords.
- decoration: new InputDecoration(
- hintText: 'Re Password',
- labelText: 'Re Enter your password'
- ),
- validator: this._validateRePassword,
- onSaved: (String value) {
- this._data.repassword = value;
- }
- ),
- new Container(
- width: screenSize.width,
- child: new RaisedButton(
- child: new Text(
- 'Submit',
- style: new TextStyle(
- color: Colors.white
- ),
- ),
- onPressed: this.submit,
- color: Colors.blue,
- ),
- margin: new EdgeInsets.only(
- top: 20.0
- ),
- )
- ],
- ),
- )
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement