Flutter with django back end
when taking a build in flutter you should add
<uses-permission android:name="android.permission.INTERNET" />
this in adoroidmanifest xml in android and then take the build
First add the http
package, save the pubspec.yaml
file.
dependencies:
flutter:
sdk: flutter
http: ^0.13.4 #
then
flutter pub get
use serializers in django and seprate views for the serializers
Future<void> signup(BuildContext context) async {
String username = userNAmeController.text;
String email = emailController.text;
String password = passwordController.text;
String rePassword = re_passwordController.text;
// Validate input
if (username.isEmpty || email.isEmpty || password.isEmpty || rePassword.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Please fill in all fields")),
);
return;
}
if (password != rePassword) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Passwords do not match")),
);
return;
}
// Prepare the data to be sent
Map<String, String> data = {
'username': username,
'email': email,
'password': password,
're_password': rePassword,
};
// Send the data to the Django backend
final response = await http.post(
Uri.parse('http://192.168.0.126:8080/register/'), // Replace with your Django URL
headers: {
'Content-Type': 'application/json', // Set the content type to JSON
},
body: json.encode(data), // Encode the data to JSON
);
// Handle the response
if (response.statusCode == 201) {
// Successfully signed up
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Signup successful")),
);
// Navigate to the HomeScreen
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);
} else {
// Handle error
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Signup failed: ${response.body}")),
);
}
}
Comments
Post a Comment