Navigator.pop()无法刷新数据库中的数据

时间:2019-10-15 03:58:21

标签: flutter dart flutter-layout

我正在尝试使用本地主机在单独的页面中使用localhost mysql创建数据,然后返回到包含Navigator.pop(context)数据列表的首页。问题是当我完成添加数据后,页面回到首页,新数据没有出现在列表中,但是在我刷新调试后,数据出现了。创建数据后,我应该怎么做才能在列表中获取新数据?

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@provide.com",
      ),
    );
  }

  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,
    });
  }



}

2 个答案:

答案 0 :(得分:1)

达到要求的一个简单技巧是从第二个屏幕弹出时传递一些数据。

>>> help(object)
Help on class object in module builtins:

class object
 |  The most base type


>>> issubclass(type,object)
True

答案 1 :(得分:0)

我终于可以解决这个问题了。这样的新数据可以在createData()函数中添加asyncawait来显示

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,
    });
  }