import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
// Entry point of the Flutter application
void main() {
runApp(MyApp());
}
// Main application widget
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
// State class for the MyApp widget
class _MyAppState extends State<MyApp> {
// Key to manage the form state
final _form = GlobalKey<FormState>();
// Variable to store the title entered by the user
String title = "";
// Function to send data to Firebase Realtime Database
void writeData() async {
// Save the form state to retrieve the input values
_form.currentState!.save();
// Firebase Realtime Database URL (replace with your database URL)
var url = "DatabaseURL" +"data.json";
// (Do not remove “data.json”, keep it as it is)
try {
// Send a POST request to the database with the title data
final response = await http.post(
Uri.parse(url),
body: json.encode({"title": title}),
);
} catch (error) {
// Handle any errors that occur during the request
throw error;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'RealTime Database',
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text("GeeksforGeeks"),
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
body: Form(
key: _form, // Assign the form key
child: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
SizedBox(
height: 10, // Add spacing between widgets
),
TextFormField(
decoration: InputDecoration(
labelText: "Enter Title", // Input field label
border: OutlineInputBorder(), // Input field border
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(
color: Colors.green.shade900,
),
),
),
onSaved: (value) {
// Save the input value to the title variable
title = value!;
},
),
SizedBox(
height: 10, // Add spacing between widgets
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
),
onPressed: writeData, // Call writeData on button press
child: Text(
"Submit", // Button text
style: TextStyle(color: Colors.white),
textAlign: TextAlign.center,
)),
],
),
),
),
),
),
);
}
}