watch the video
pubspec.yaml
name: reg_user_proj
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: '>=2.19.0 <3.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
http: ^0.13.5
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
main.dart
import 'package:flutter/material.dart';
import './service.dart';
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(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const RegisterPage(),
//for debug show checjed mode banner
debugShowCheckedModeBanner: false,
);
}
}
class RegisterPage extends StatefulWidget {
const RegisterPage({super.key});
@override
State<RegisterPage> createState() => _RegisterPageState();
}
class _RegisterPageState extends State<RegisterPage> {
TextEditingController nameController = TextEditingController();
TextEditingController emailController = TextEditingController();
TextEditingController addressController = TextEditingController();
TextEditingController mobileController = TextEditingController();
//create the service class object
Service service = Service();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Registration Page'),
),
body: Container(
padding: EdgeInsets.all(20),
child: ListView(
children: [
Text('Name'),
SizedBox(
height: 5,
),
TextField(
controller: nameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter Name',
),
),
//for some space bwtween fields
SizedBox(
height: 10,
),
Text('Email'),
SizedBox(
height: 5,
),
TextField(
controller: emailController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter Email',
),
),
//for some space bwtween fields
SizedBox(
height: 10,
),
Text('Mobile'),
SizedBox(
height: 5,
),
TextField(
controller: mobileController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter Mobile',
),
),
//for some space bwtween fields
SizedBox(
height: 10,
),
Text('Address'),
SizedBox(
height: 5,
),
TextField(
controller: addressController,
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Enter Address',
),
),
//for some space bwtween fields
SizedBox(
height: 10,
),
ElevatedButton(
onPressed: () {
service.saveUser(nameController.text, mobileController.text,
emailController.text, addressController.text);
},
child: Text(
'Register',
style: TextStyle(
fontSize: 25,
),
),
)
],
),
),
);
}
}
service.dart
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
class Service {
//create the method to save user
Future<http.Response> saveUser(
String name, String mobile, String email, String address) async {
//create uri
var uri = Uri.parse("http://localhost:8080/register");
//header
Map<String, String> headers = {"Content-Type": "application/json"};
//body
Map data = {
'name': '$name',
'email': '$email',
'mobile': '$mobile',
'address': '$address',
};
//convert the above data into json
var body = json.encode(data);
var response = await http.post(uri, headers: headers, body: body);
//print the response body
print("${response.body}");
return response;
}
}
spring boot
directory structure
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringBootRegister</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBootRegister</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
#datasource peoperties
spring.datasource.url=jdbc:mysql://localhost:3306/new
#new is the schema name i have created in myql
#give password and username of the mysql
spring.datasource.username=root
spring.datasource.password=root
#jpa related
spring.jpa.hibernate.ddl-auto=update
#update mean if table not present then create tab
User.java
package com.example.demo.entity;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data//for getter and setter method add lombok anotation
@AllArgsConstructor//lombok anno
@NoArgsConstructor
@Entity//to create the table
@Table(name = "user_tab")//for the table name
public class User {
@Id//for id to be primary key
//below annotation to auto increment the id value
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String email;
private String mobile;
private String address;
}
UserRepo
package com.example.demo.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.User;
public interface UserRepo extends JpaRepository<User, Integer>{
}
UserService.java
package com.example.demo.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.entity.User;
import com.example.demo.repo.UserRepo;
@Service
public class UserService {
@Autowired
private UserRepo repo;
public String saveUser(User user) {
repo.save(user);
return "User registered Successfully";
}
}
UserController
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
@RestController
@CrossOrigin//dont forgot to add this
public class UserController {
@Autowired
private UserService service;
@PostMapping("/register")
private ResponseEntity<String> registerUser(@RequestBody User user){
//save the user
String msg = service.saveUser(user);
return new ResponseEntity<String>(msg,HttpStatus.OK);
}
}