Skip to content

Latest commit

 

History

History
200 lines (179 loc) · 6.74 KB

002.6.APP_APOTEK_FLUTTERFIRE.md

File metadata and controls

200 lines (179 loc) · 6.74 KB

SUDAH MENGIKUTI LANGKAH 5️⃣.

Sekarang kita lanjutkan ke Edit Data Pemeriksaan. Fitur ini memungkinkan admin untuk memperbarui data hasil pemeriksaan yang sudah tersimpan di Firebase Firestore.


Langkah 1: Tambahkan Tombol Edit di Laporan Pemeriksaan

Modifikasi medical_report_screen.dart

Tambahkan tombol Edit pada setiap item laporan pemeriksaan.

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'edit_medical_check_screen.dart';

class MedicalReportScreen extends StatelessWidget {
  const MedicalReportScreen({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Laporan Hasil Pemeriksaan')),
      body: StreamBuilder<QuerySnapshot>(
        stream:
            FirebaseFirestore.instance.collection('medical_checks').snapshots(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (!snapshot.hasData || snapshot.data!.docs.isEmpty) {
            return const Center(child: Text('Tidak ada hasil pemeriksaan.'));
          }

          final checks = snapshot.data!.docs;

          return ListView.builder(
            itemCount: checks.length,
            itemBuilder: (context, index) {
              final data = checks[index].data() as Map<String, dynamic>;
              return Card(
                margin: const EdgeInsets.all(8.0),
                child: ListTile(
                  title: Text('ID Pasien: ${data['patientId']}'),
                  subtitle: Text(
                    'Suhu: ${data['suhu']} °C\n'
                    'Tekanan Darah: ${data['tekananDarah']}\n'
                    'Diagnosa: ${data['diagnosa']}\n'
                    'Obat: ${data['obat']} (${data['dosis']})',
                  ),
                  trailing: IconButton(
                    icon: const Icon(Icons.edit),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => EditMedicalCheckScreen(
                            checkId: checks[index].id,
                          ),
                        ),
                      );
                    },
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

Langkah 2: Buat Layar Edit Pemeriksaan

Buat File Baru: screens/edit_medical_check_screen.dart

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

class EditMedicalCheckScreen extends StatefulWidget {
  final String checkId;

  EditMedicalCheckScreen({required this.checkId});

  @override
  _EditMedicalCheckScreenState createState() => _EditMedicalCheckScreenState();
}

class _EditMedicalCheckScreenState extends State<EditMedicalCheckScreen> {
  final _formKey = GlobalKey<FormState>();
  Map<String, dynamic> checkData = {};

  @override
  void initState() {
    super.initState();
    _fetchCheckData();
  }

  void _fetchCheckData() async {
    DocumentSnapshot doc = await FirebaseFirestore.instance
        .collection('medical_checks')
        .doc(widget.checkId)
        .get();
    if (doc.exists) {
      setState(() {
        checkData = doc.data() as Map<String, dynamic>;
      });
    }
  }

  void _saveChanges() async {
    if (_formKey.currentState!.validate()) {
      try {
        await FirebaseFirestore.instance
            .collection('medical_checks')
            .doc(widget.checkId)
            .update(checkData);
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Data pemeriksaan berhasil diperbarui!')),
        );
        Navigator.pop(context);
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Gagal memperbarui data: $e')),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Edit Data Pemeriksaan')),
      body: checkData.isEmpty
          ? Center(child: CircularProgressIndicator())
          : Padding(
              padding: const EdgeInsets.all(16.0),
              child: Form(
                key: _formKey,
                child: ListView(
                  children: [
                    TextFormField(
                      initialValue: checkData['suhu'].toString(),
                      decoration: InputDecoration(labelText: 'Suhu (°C)'),
                      onChanged: (value) =>
                          checkData['suhu'] = double.tryParse(value) ?? 0.0,
                      validator: (value) =>
                          value!.isEmpty ? 'Suhu tidak boleh kosong' : null,
                    ),
                    TextFormField(
                      initialValue: checkData['tekananDarah'],
                      decoration: InputDecoration(labelText: 'Tekanan Darah'),
                      onChanged: (value) => checkData['tekananDarah'] = value,
                    ),
                    TextFormField(
                      initialValue: checkData['diagnosa'],
                      decoration: InputDecoration(labelText: 'Diagnosa'),
                      onChanged: (value) => checkData['diagnosa'] = value,
                    ),
                    TextFormField(
                      initialValue: checkData['obat'],
                      decoration: InputDecoration(labelText: 'Obat'),
                      onChanged: (value) => checkData['obat'] = value,
                    ),
                    TextFormField(
                      initialValue: checkData['dosis'].toString(),
                      decoration: InputDecoration(labelText: 'Dosis (per hari)'),
                      onChanged: (value) =>
                          checkData['dosis'] = int.tryParse(value) ?? 0,
                    ),
                    SizedBox(height: 20),
                    ElevatedButton(
                      onPressed: _saveChanges,
                      child: Text('Simpan Perubahan'),
                    ),
                  ],
                ),
              ),
            ),
    );
  }
}

Langkah 3: Testing

  1. Jalankan aplikasi dan buka Laporan Hasil Pemeriksaan.
  2. Klik tombol Edit di salah satu hasil pemeriksaan.
  3. Ubah data (misalnya, diagnosa, obat, atau dosis) dan tekan Simpan Perubahan.
  4. Periksa apakah data di Firestore sudah terupdate.

Next Step

Fitur utama selesai! 🚀

DAN YAP USAI SUDAH SERIES INI.🥳

SEE NEXT TIME! 😏