Here are the codes used in the video:
Back end API in PHP:
get_contacts.php
<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
include "connection-pdo.php";
$userId = $_GET['userId'];
$sql = "SELECT * FROM tblcontacts WHERE contact_userId = :userId ";
$sql .= "ORDER BY contact_name ";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":userId", $userId);
$stmt->execute();
$returnValue = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($returnValue);
?>
Front end
Flutter Code:
main.dart for the login
import 'dart:convert';
import 'package:db/contacts_list.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),
),
],
),
)),
);
}
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";
});
}
}
}
contacts_list.dart for the Contacts List
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(
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 [];
}
}
}
No comments:
Post a Comment