Back end:
register.php
<?php
include "headers.php";
include "connection-pdo.php";
$username = $_POST['username'];
$password = $_POST['password'];
$fullname = $_POST['fullname'];
$sql = "INSERT INTO tblusers(usr_username, usr_password, usr_fullname) ";
$sql .= "VALUES (:username, :password, :fullname) ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":username", $username);
$stmt->bindParam(":password", $password);
$stmt->bindParam(":fullname", $fullname);
$stmt->execute();
$returnValue = $stmt->rowCount() > 0 ? 1 : 0;
echo json_encode($returnValue);
?>
Front end:
main.dart (login)
import 'dart:convert';
import 'package:db/contacts_list.dart';
import 'package:db/register.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Sample API'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _msg = "";
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
const SizedBox(
height: 30.0,
),
const Text(
"Login",
style: TextStyle(fontSize: 20.0),
),
TextField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: "Username", hintText: "Enter Username"),
),
const SizedBox(
height: 30.0,
),
TextField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: "Password", hintText: "Enter Password"),
),
const SizedBox(
height: 30.0,
),
ElevatedButton(
onPressed: () {
login();
},
child: const Text(
"Login",
),
),
const SizedBox(
height: 30.0,
),
Text(
_msg,
style: const TextStyle(fontSize: 20.0),
),
const SizedBox(
height: 30.0,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Register(),
),
);
},
child: const Text(
"No account yet? Register here...",
style: TextStyle(
color: Colors.blue,
fontStyle: FontStyle.italic,
decoration: TextDecoration.underline,
fontSize: 20.0,
),
),
)
],
),
)),
);
}
void login() async {
String url = "http://localhost/flutter/api/login.php";
final Map<String, dynamic> queryParams = {
"username": _usernameController.text,
"password": _passwordController.text
};
try {
http.Response response =
await http.get(Uri.parse(url).replace(queryParameters: queryParams));
if (response.statusCode == 200) {
var user = jsonDecode(response.body); //return type list<Map>
if (user.isNotEmpty) {
//navigate to next page
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ContactsList(
userId: user[0]['usr_id'],
userFullName: user[0]['usr_fullname']),
),
);
} else {
setState(() {
_msg = "Invalid Username or password.";
});
}
} else {
setState(() {
_msg = "${response.statusCode} ${response.reasonPhrase}";
});
}
} catch (error) {
setState(() {
_msg = "$error";
});
}
}
}
register.dart
import 'package:db/functions/public_functions.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class Register extends StatefulWidget {
const Register({Key? key}) : super(key: key);
@override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
TextEditingController usernameController = TextEditingController();
TextEditingController passwordController = TextEditingController();
TextEditingController fullnameController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Contacts Database"),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
children: [
const Text(
"User Registration",
style: TextStyle(
fontSize: 20.0,
),
),
const SizedBox(
height: 20.0,
),
TextField(
controller: usernameController,
decoration: const InputDecoration(
labelText: "Username",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.person),
),
),
const SizedBox(
height: 10.0,
),
TextField(
controller: passwordController,
decoration: const InputDecoration(
labelText: "Password",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.password),
),
),
const SizedBox(
height: 10.0,
),
TextField(
controller: fullnameController,
decoration: const InputDecoration(
labelText: "Full Name",
border: OutlineInputBorder(),
suffixIcon: Icon(Icons.abc),
),
),
const SizedBox(
height: 20.0,
),
ElevatedButton(
onPressed: () {
save();
},
child: const Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.save,
),
SizedBox(
width: 10.0,
),
Text("Save"),
],
),
),
],
),
),
),
);
}
void save() async {
Uri uri = Uri.parse('http://localhost/flutter/api/register.php');
Map<String, dynamic> data = {
"username": usernameController.text,
"password": passwordController.text,
"fullname": fullnameController.text,
};
http.Response response = await http.post(uri, body: data);
print(response.body);
if (response.statusCode == 200) {
if (response.body == "1") {
showMessageBox(context, "Success", "You have successfully registered!");
} else {
showMessageBox(context, "Error", "Registration failed!");
}
} else {
showMessageBox(context, "Error",
"The server returned a ${response.statusCode} error.");
}
}
}
contacts_list.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class ContactsList extends StatefulWidget {
final int userId;
final String userFullName;
const ContactsList(
{super.key, required this.userId, required this.userFullName});
@override
_ContactsListState createState() => _ContactsListState();
}
class _ContactsListState extends State<ContactsList> {
List<dynamic> _contactsList = [];
@override
void didChangeDependencies() async {
super.didChangeDependencies();
List myList = await getContacts();
setState(() {
_contactsList = myList;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Contacts List"),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.blue,
child: const Icon(Icons.add),
),
body: Center(
child: Column(
children: [
const Text(
"My Contacts",
style: TextStyle(
fontSize: 20.0,
),
),
//litView
Expanded(
child: FutureBuilder(
future: getContacts(),
builder: (context, snapShot) {
switch (snapShot.connectionState) {
case ConnectionState.waiting:
return const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(),
SizedBox(
height: 20.0,
),
Text("Loading..."),
],
);
case ConnectionState.done:
if (snapShot.hasError) {
return Text("Error while: ${snapShot.error}");
}
//display listView here
return contactsListView();
default:
return Text("Error while: ${snapShot.error}");
}
}),
),
Text(
"Current User - ${widget.userFullName}",
style: const TextStyle(
fontSize: 20.0,
),
),
],
),
),
);
}
Widget contactsListView() {
return ListView.builder(
itemCount: _contactsList.length,
itemBuilder: (context, index) {
return Card(
child: ListTile(
leading: const Icon(Icons.phone),
title: Text(_contactsList[index]['contact_name']),
subtitle: Text(_contactsList[index]['contact_phone']),
trailing: const Icon(Icons.arrow_right),
),
);
},
);
}
Future<List> getContacts() async {
// await Future.delayed(
// const Duration(seconds: 3),
// );
String url = "http://localhost/flutter/api/get_contacts.php";
final Map<String, dynamic> queryParams = {
"userId": widget.userId.toString(),
};
http.Response response = await http.get(
Uri.parse(url).replace(queryParameters: queryParams),
);
if (response.statusCode == 200) {
var contacts = jsonDecode(response.body);
return contacts;
} else {
return [];
}
}
}
public_functions.dart
import 'package:flutter/material.dart';
void showMessageBox(BuildContext context, String title, String content) {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(title),
content: Text(content),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text("OK"),
),
],
);
},
);
}
No comments:
Post a Comment