Flutterize : Membuat Todo List App Menggunakan Flutter dan Cloud Firestore (PART 4)

Setelah pada artikel sebelumnya kita sudah bisa membuat operasi delete, selanjutnya kita akan membuat operasi update pada aplikasi yang kita buat sebelumnya.

Pertama, buat screen untuk form update. Beri nama class nya UpdateScreen.

Sehingga kodenya menjadi seperti ini.

class UpdateScreen extends StatefulWidget {
final String documentId;
final String task;
final String description;
const UpdateScreen({Key key, this.documentId, this.task, this.description}) : super(key: key);

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

class _UpdateScreenState extends State<UpdateScreen> {
@override
Widget build(BuildContext context) {
return Scaffold();
}
}

Jangan lupa untuk menambahkan property pada class UpdateScreen untuk menampung kiriman data dari layar sebelumnya.

Tambahkan parameter onTap pada widget ListTile. Berikan code untuk berpindah screen ke UpdateScreen.

ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UpdateScreen(
description: snapshot.data.documents[index]['task'],
documentId: snapshot.data.documents[index].documentID,
task: snapshot.data.documents[index]['task'],
),
));
},
title: Text(snapshot.data.documents[index]['task']),
subtitle: Text(snapshot.data.documents[index]['description']),
),

Selanjutnya, tambahkan property GlobalKey untuk FormState. Juga TextEdittingController untuk TextFormField title dan description.

final updateFormKey = GlobalKey<FormState>();
TextEditingController titleTaskController = TextEditingController();
TextEditingController descTaskController = TextEditingController();

Lalu isi teks dari TextFormField nya dengan cara memanggil TextEdittingController nya pada override method initState().

@override
  void initState() {
    super.initState();
    titleTaskController.text = widget.task;
    descTaskController.text = widget.description;
  }

Selanjutnya, buat layout untuk tamnpilan UpdateScreen

    return Scaffold(
      appBar: AppBar(
        title: Text("Update Task"),
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: Icon(Icons.arrow_back),
        ),
      ),
      body: SingleChildScrollView(
        padding: EdgeInsets.all(20),
        child: Form(
          autovalidateMode: AutovalidateMode.always,
          key: updateFormKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                "Task Name",
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(
                height: 8,
              ),
              TextFormField(
                validator: (value) {
                  if (value.isEmpty || value.trim().length == 0) {
                    return "Task name cannot be empty";
                  }
                  return null;
                },
                controller: titleTaskController,
                style: TextStyle(
                  color: Colors.black,
                ),
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "Update Task Name....",
                ),
              ),
              SizedBox(
                height: 12,
              ),
              Text(
                "Task Description",
                style: TextStyle(
                  fontWeight: FontWeight.w600,
                ),
              ),
              SizedBox(
                height: 8,
              ),
              TextFormField(
                controller: descTaskController,
                validator: (value) {
                  if (value.isEmpty || value.trim().length == 0) {
                    return "Task description cannot be empty";
                  }
                  return null;
                },
                style: TextStyle(
                  color: Colors.black,
                ),
                maxLines: 4,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: "Update Task Description....",
                ),
              ),
              SizedBox(
                height: 24,
              ),
              FlatButton(
                minWidth: MediaQuery.of(context).size.width,
                padding: EdgeInsets.all(10),
                color: Colors.blue,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  "Submit",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 20,
                  ),
                ),
                onPressed: () async {
                },
              ),
            ],
          ),
        ),
      ),
    );

Lalu tambahkan code proses update ketika tomboy submit di tekan.

if (updateFormKey.currentState.validate()) {
progressDialog(context).show();

Firestore firestore = Firestore.instance;

DocumentReference reference = firestore.document("todo/${widget.documentId}");
firestore.runTransaction((transaction) async {
DocumentSnapshot snapshot = await transaction.get(reference);

if (snapshot.exists){
transaction.update(reference, <String, dynamic>{
'task': titleTaskController.text.toString(),
'description': descTaskController.text.toString(),
}).then((value) {
progressDialog(context).hide();
successAlert("Success", "Success Insert Task", context);
}).catchError((error){
progressDialog(context).hide();
errorAlert("Failed", "Failed to Insert Task", context);
});
}

}).then((value) {
progressDialog(context).hide();
successAlert("Success", "Success Insert Task", context);
}).catchError((error){
progressDialog(context).hide();
errorAlert("Failed", "Failed to Insert Task", context);
});

} else {
errorAlert("Failed", "Please fill all the fields", context);
}

Untuk final aplikasi bisa kalian clone project di link GitHub dibawah.

See Ya’

Link Project : Github

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top