Introduction To Dart Programming Language
- Overview
- Environment
- Variables
- Operators
Signup.dart
import 'package:flutter/material.dart';
import 'main.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'account.dart';
import 'functions.dart';
class Signup extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Socialize',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Sign Up Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State {
// For CircularProgressIndicator.
bool visible = false ;
String password = "";
final _formKey = GlobalKey();
final _scaffoldKey = GlobalKey();
// Getting value from TextField widget.
final nameController = TextEditingController();
final emailController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();
Future signup() async{
// Showing CircularProgressIndicator.
setState(() {
visible = true ;
});
String name = nameController.text;
String email = emailController.text;
String password = passwordController.text;
// SERVER SIGN UP API URL
var url = 'http://192.168.43.94/socialize/signup.php';
// Store all data with Param Name.
var data = {'name': name, 'email': email, 'password': password};
// Starting Web API Call.
var response = await http.post(url, body: json.encode(data));
// Getting Server response into variable.
Mapdynamic> responseJson = jsonDecode(response.body);
var message = responseJson['message'];
var success = responseJson['success'];
var session = responseJson['session'];
//If account is successfully created, set session shared preference and redirect to account page
if(success==1){
//Set animation progress to invisible
setState(() {
visible = false ;
});
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(message)));
setSession(session);
}else{
//Set animation progress to invisible
setState(() {
visible = false ;
});
//Show response from the server
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(message)));
}
}
Future setSession(String session) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('session', session);
//Redirect to account page
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Account())
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key:_scaffoldKey,
body: Stack(
children: [
Container(
decoration: new BoxDecoration(
image: new DecorationImage(
fit: BoxFit.cover,
image: AssetImage("assets/bg.jpg"), //Background image
)),
),
Center(
child: SingleChildScrollView(
padding: EdgeInsets.all(30.0),
child:Form(
key: _formKey,
child: Column(
children: [
SizedBox(
height: 60.0,
),
SizedBox(
height: 70.0,
child: Image.asset(
"assets/logo.png",
fit: BoxFit.contain,
),
),
SizedBox(
height: 60.0,
),
TextFormField(
controller: nameController,
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Please enter your name';
}
return null;
},
decoration: InputDecoration(
prefixIcon: Icon(
Icons.person,
color: Colors.white,
),
hintStyle: TextStyle(color: Colors.white),
filled: true,
fillColor: Colors.black45,
hintText: 'Name',
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(30.0))
),
),
SizedBox(
height: 10.0,
),
TextFormField(
controller: emailController,
keyboardType: TextInputType.emailAddress,
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Please enter your email address';
}else if(!new Functions().validate_email(value)){
return 'Please email is not in the correct format';
}
return null;
},
decoration: InputDecoration(
prefixIcon: Icon(
Icons.email,
color: Colors.white,
),
hintStyle: TextStyle(color: Colors.white),
filled: true,
fillColor: Colors.black45,
hintText: 'Email',
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(30.0))
),
),
SizedBox(
height: 10.0,
),
TextFormField(
obscureText: true,
controller: passwordController,
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Please enter your password';
}else if(!new Functions().validate_password(value)){
return 'Password must be at least 5 characters long';
}else {
password = value;
return null;
}
},
decoration: InputDecoration(
filled: true,
prefixIcon: Icon(Icons.lock, color: Colors.white),
hintStyle: TextStyle(color: Colors.white),
fillColor: Colors.black45,
hintText: 'Password',
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(30.0))
),
),
SizedBox(
height: 10.0,
),
TextFormField(
obscureText: true,
controller: confirmPasswordController,
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Please re-enter password';
}else if(value !=password){
return "Confirm password and password fields don't match";
}
return null;
},
decoration: InputDecoration(
filled: true,
prefixIcon: Icon(Icons.lock, color: Colors.white),
hintStyle: TextStyle(color: Colors.white),
fillColor: Colors.black45,
hintText: 'Confirm Password',
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(30.0))
),
),
SizedBox(
height: 15.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
height: 15.0,
),
RaisedButton(
onPressed: () {
// Validate returns true if the form is valid, otherwise false.
if (_formKey.currentState.validate()) {
//Process form
signup();
}
},
child: Padding(
padding: EdgeInsets.all(15.0),
child: Text('SIGN UP')),
color: Colors.redAccent,
textColor: Colors.white,
),
],
),
SizedBox(
child: Visibility(
visible: visible,
child: Container(
margin: EdgeInsets.only(top: 10),
child:SizedBox(
width:20,
height:20,
child:CircularProgressIndicator()
),
)
),
),
SizedBox(
height: 20.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Divider(
color: Colors.black,
height: 8.0,
),
),
SizedBox(
width: 8.0,
),
Text(
'OR',
style: TextStyle(color: Colors.black),
),
SizedBox(
width: 8.0,
),
Expanded(
child: Divider(
color: Colors.black,
height: 8.0,
),
)
],
),
],
),
SizedBox(
height: 20.0,
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// TODO Social Icons
RaisedButton(
onPressed: () {
// Load the sign up page.
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp())
);
},
child: Padding(
padding: EdgeInsets.all(15.0),
child: Text('LOGIN')),
color: Colors.blue,
textColor: Colors.white,
),
],
),
],
),
),
),
),
],
),
);
}
}
NOTE
var url = 'http://192.168.43.94/socialize/signup.php';
Use your ip address instead if you are using physical phone for testing. Your phone must be in the same network as your computer. Thus they must be connected to the same wireless network. If you are using your phone for the internet, it means your computer internet source must be from the phone by connecting the computer to the phone's wireless network through hotspot.
To determine your ip address, open the command prompt and run ipconfig.
Figure: ipconfig command
As you already know from week 1, to open the command prompt window, you can search cmd in the search bar for searching apps on the computer.
If you are using virtual device for the testing of your app, you can change the ip address to localhost since your testing device (virtual device) is on the machine where the server is located. Thus:
var url = 'http://localhost/socialize/signup.php';
Sign up page
account.dart
import 'package:flutter/material.dart';
import 'home.dart';
import 'online.dart';
import 'profile.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'main.dart';
/// This Widget is the main application widget.
class Account extends StatelessWidget {
static const String _title = 'Kuulchat Flutter Tutorials';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyAppStatefulWidget(),
);
}
}
class MyAppStatefulWidget extends StatefulWidget {
MyAppStatefulWidget({Key key}) : super(key: key);
@override
_MyApp createState() => _MyApp();
}
class _MyApp extends State{
int _currentIndex = 0;
final _scaffoldKey = GlobalKey();
final List _children = [
Home(),
Online(),
Profile()
];
void _select(Choice choice) {
String selected = choice.title;
if(selected=="Logout"){
logout();
}else if(selected=="Settings"){
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Navigate to settings page")));
}
}
Future logout() async{
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Signing you out ...")));
SharedPreferences prefs = await SharedPreferences.getInstance();
String session = (prefs.getString('session') ?? "");
// SERVER SIGN UP API URL
var url = 'http://192.168.43.94/socialize/logout.php';
// Store all data with Param Name.
var data = {'session': session};
// Starting Web API Call.
var response = await http.post(url, body: json.encode(data));
// Getting Server response into variable.
Mapdynamic> responseJson = jsonDecode(response.body);
var success = responseJson['success'];
//If account is successfully created, set session shared preference and redirect to account page
if(success==1){
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("You've logged out.")));
//Remove shared preference and navigate to login page
prefs.remove("session");
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyApp())
);
}else{
//Show response from the server
_scaffoldKey.currentState.showSnackBar(SnackBar(content: Text("Failed to logout. Try again later.")));
//Set animation progress to invisible
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Kuulchat Flutter Tutorials',
home: Scaffold(
key:_scaffoldKey,
appBar: AppBar(
title: Text('Socialize'),
actions: [
PopupMenuButton(
onSelected: _select,
color:Colors.blue,
itemBuilder: (BuildContext context) {
return choices.skip(0).map((Choice choice) {
return PopupMenuItem(
value: choice,
child: ListTile(
title: Text(choice.title,
style: TextStyle(
color: Colors.white,
)),
leading: Icon(choice.icon, color: Colors.white),
)
);
}).toList();
},
),
],
),
body:_children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currentIndex,
onTap: tabSelected, // this will be set when a new tab is tapped
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.chat),
title: new Text('Chats'),
),
BottomNavigationBarItem(
icon: new Icon(Icons.group),
title: new Text('Online'),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_circle),
title: Text('Profile')
)
],
),
),
);
}
void tabSelected(int index) {
setState(() {
_currentIndex = index;
});
}
}
class Choice {
const Choice({this.title, this.icon});
final String title;
final IconData icon;
}
const List choices = const [
const Choice(title: 'Settings', icon: Icons.settings),
const Choice(title: 'Logout', icon: Icons.power_settings_new),
];
home.dart
import 'package:flutter/material.dart';
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child:Container(
child: Text("Chat content widgets come here"),
),
);
}
}
Account home page
online.dart
import 'package:flutter/material.dart';
class Online extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child:Container(
child: Text("Online content widgets come here"),
),
);
}
}
Online page
profile.dart
import 'package:flutter/material.dart';
class Profile extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child:Container(
child: Text("Profile content widgets come here"),
),
);
}
}
Profile page
Asset Images
bg.jpg
logo.png