Muhammad Heryan
Muhammad Heryan

Reputation: 26

Navigator.pop() not refresh data from database

I am trying to make create data with localhost mysql in separate page with home and after that go back to home that contain list of data with Navigator.pop(context). the problem is when i've done add data, the page go back to home and new data not appear in list, but after i refresh debug the data appear. what should i do to get new data in list after create data?

main.dart

import "package:flutter/material.dart";
import "dart:async";
import 'package:http/http.dart' as http;
import 'dart:convert';
import "Detail.dart";
import "CreatePegawai.dart";

void main() {
  runApp(new MaterialApp(
    title: "CRUD PEGAWAI",
    home: new Home(),
  ));
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Future<List> readData() async {
    final response = await http.get("http://10.0.2.2/modelpegawai/read.php");
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: new AppBar(
        title: new Text("List Data Pegawai"),
        leading: new Icon(Icons.home),
        backgroundColor: Colors.blue[300],
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.add),
        onPressed: ()=>Navigator.of(context).push(
          new MaterialPageRoute(
            builder: (BuildContext context)=> new CreatePegawai(),
          )
        ),
      ),
      body: new FutureBuilder<List>(
        future: readData(),
        builder: (context, snapshot) {
          if (snapshot.hasError) {
            print(snapshot.error);
          }

          return snapshot.hasData
              ? new ItemList(list: snapshot.data)
              : new Center(
                  child: new CircularProgressIndicator(),
                );
        },
      ),
      backgroundColor: Colors.yellow[200],
    );
  }
}

class ItemList extends StatelessWidget {
  final List list;
  ItemList({this.list});

  @override
  Widget build(BuildContext context) {
    return new ListView.builder(
        itemCount: list == null ? 0 : list.length,
        itemBuilder: (context, i) {
          return new Container(
            padding: const EdgeInsets.all(10.0),
            child: new GestureDetector(
              onTap: ()=>Navigator.of(context).push(
                new MaterialPageRoute(
                  builder: (BuildContext context)=>new Detail(list:list, index:i)
                )
              ),
                child: new Card(
                    child: new ListTile(
                      title: new Text(
                        list[i]['nama'],
                        style: new TextStyle(fontSize: 20.0),
                      ),
                      leading: new Icon(Icons.assignment_ind),
                      subtitle: new Text(
                        "Asal : ${list[i]['asalKota']}",
                        style: new TextStyle(fontSize: 16.0),
                      ),
                )),
              ));
        });
  }
}

createPegawai.dart

import "package:flutter/material.dart";
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:datetime_picker_formfield/datetime_picker_formfield.dart';

class CreatePegawai extends StatefulWidget {
  @override
  _CreatePegawaiState createState() => _CreatePegawaiState();
}

class _CreatePegawaiState extends State<CreatePegawai> {
  DateTime date2;
  TextEditingController controllerNIP = new TextEditingController();
  TextEditingController controllerNama = new TextEditingController();
  TextEditingController controllerTgl = new TextEditingController();
  TextEditingController controllerAsalKota = new TextEditingController();
  TextEditingController controllerDept = new TextEditingController();
  TextEditingController controllerEmail = new TextEditingController();
  TextEditingController controllerPass = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: new AppBar(
          title: new Text("Tambah Pegawai"),
        ),
        body: Padding(
          padding: const EdgeInsets.all(20.0),
          child: ListView(
            children: <Widget>[
              new Column(
                children: <Widget>[
                  new Text(
                    "Form Tambah Pegawai",
                    style: new TextStyle(
                      fontSize: 20.0,
                    ),
                  ),
                  nip(),
                  nama(),
                  tgl(),
                  asalKota(),
                  kodeDept(),
                  email(),
                  pass(),
                  new Padding(
                    padding: const EdgeInsets.all(10.0),
                  ),
                  tombol(),
                ],
              ),
            ],
          ),
        ));
  }

  Widget nip() {
    return TextField(
      controller: controllerNIP,
      decoration: new InputDecoration(
        hintText: "NIP 3 Angka",
        labelText: "NIP",
      ),
    );
  }

  Widget nama() {
    return TextField(
      controller: controllerNama,
      decoration: new InputDecoration(
        hintText: "Masukan Nama",
        labelText: "Nama",
      ),
    );
  }

  Widget tgl() {
    return new Container(
      child: DateTimePickerFormField(
        controller: controllerTgl,
        inputType: InputType.date,
        format: DateFormat("dd-MM-yyyy"),
        initialDate: DateTime(2019, 1, 1),
        editable: false,
        decoration:
            InputDecoration(labelText: 'Date', hasFloatingPlaceholder: false),
        onChanged: (dt) {
          setState(() => date2 = dt);
        },
      ),
    );
  }

  Widget asalKota() {
    return TextField(
      controller: controllerAsalKota,
      decoration: new InputDecoration(
        hintText: "Masukan Kota Asal",
        labelText: "Kota Asal",
      ),
    );
  }

  Widget kodeDept() {
    return TextField(
      controller: controllerDept,
      decoration: new InputDecoration(
        hintText: "Dept",
        labelText: "Departmen",
      ),
    );
  }

  Widget email() {
    return TextFormField(
      controller: controllerEmail,
      keyboardType: TextInputType.emailAddress, //KEYBOARD TYPENYA ADALAH EMAIL ADDRESS AGAR SYMBOL @ DILETAKKAN DIDEPAN KETIKA KEYBOARD DI TAMPILKAN
      decoration: InputDecoration(
        labelText: "Email",
        hintText: "[email protected]",
      ),
    );
  }

  Widget pass() {
    return TextFormField(
      controller: controllerPass,
      obscureText: true, //membuat titik2 pada inputan/tidak keliatan text
      decoration: InputDecoration(
        labelText: "Password",
        hintText: "Masukan password",
      ),
    );
  }

  Widget tombol() {
    return RaisedButton(
      child: new Text("Tambah"),
      color: Colors.blueAccent,
      onPressed: () {
        create();
        Navigator.pop(context);
      },
    );
  }

  void create(){
    var url = "http://10.0.2.2/modelpegawai/create.php";
    var formatter = new DateFormat('yyyy-MM-dd');
    String formatted = formatter.format(date2);



    http.post(url, body:{
      "nip": controllerNIP.text,
      "nama": controllerNama.text,
      "tgl": formatted,
      "asalKota": controllerAsalKota.text,
      "dept": controllerDept.text,
      "email": controllerEmail.text,
      "pass": controllerPass.text,
    });
  }



}

Upvotes: 0

Views: 1140

Answers (2)

Muhammad Heryan
Muhammad Heryan

Reputation: 26

I Finally can solve this problem. the new data can show with add async and await in the createData() function like this

void create() async {
    var url = "http://10.0.2.2/modelpegawai/create.php";
    var formatter = new DateFormat('yyyy-MM-dd');
    String formatted = formatter.format(date2);



    await http.post(url, body:{
      "nip": controllerNIP.text,
      "nama": controllerNama.text,
      "tgl": formatted,
      "asalKota": controllerAsalKota.text,
      "dept": controllerDept.text,
      "email": controllerEmail.text,
      "pass": controllerPass.text,
    });
  }

Upvotes: 0

A simple trick to achieve your requirement is pass some data when poping from second screen.

// This is where you push to second screen from first screen
// Make sure you a method to get data from server
// And call that function when popped

Navigator.of(context).push(
     MaterialPageRoute(
           builder: (context) => SecondScreen())).then(
                (data){
                  if(data!=null && data){
                        getDataFromServer();  
                   });

// This is where you are poping from second screen.
// Pass a bool whether you want refresh first screen or not.
Navigator.of(context).pop(true)

Upvotes: 1

Related Questions