Flutter:一旦我通过底部导航栏导航到下一个屏幕,就不会填充数据

时间:2018-10-06 07:35:45

标签: database flutter state

我的一个项目需要帮助。 我有一个带有三个标签的底部导航栏。在第二页中,我正在通过弹出窗口将数据添加到数据库,然后将其显示在列表中。 我能够添加和显示数据。但是我导航到另一个屏幕,然后返回数据不存在,不确定发生了什么?

Refer the screenshot

还有另一件事navigator.pop无法关闭对话框。

   //Database class

class DatabaseHelper{

  static final DatabaseHelper _instance = new DatabaseHelper.internal();
  factory DatabaseHelper() => _instance;

  static Database _db;

  Future<Database> get db async{
    if(_db != null){
      return _db;
    }
      _db = await initDb();
      return _db;

  }

  DatabaseHelper.internal();

  initDb() async{

    io.Directory documentDirectry = await getApplicationDocumentsDirectory();
    String path = join(documentDirectry.path, "DataBaseV.db");
    var ourDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return ourDb;
  }

  void _onCreate(Database db, int version) async{
    await db.execute("CREATE TABLE ControllerTable(ControllerId INTEGER PRIMARY KEY, ControllerName TEXT, ControllerNumber TEXT, ControllerDateCreated TEXT)");
    print("Controller table is created");
  }

  //insertion
  Future<int> saveController(Controller controllerTable) async{
    var dbClient = await db;
    int res = await dbClient.insert("ControllerTable", controllerTable.toMap());
    return res;
  }

  //Get from database
  Future<List> getItems() async{
    var dbClient = await db;
    var result = await dbClient.rawQuery("SELECT * FROM ControllerTable");
    return result.toList();
  }

  Future<Controller> getItem(int id) async{
    var dbClient = await db;
    var result = await dbClient.rawQuery("SELECT * FROM ControllerTable WHERE ControllerId = $id");
    if(result.length == 0) return null;
    return new Controller.fromMap(result.first);
  }

  Future close() async{
    var dbClient = await db;
    return dbClient.close();
  }
}


//Model Class

class Controller extends StatelessWidget {

  String _ControllerName;
  String _ControllerNumber;
  String _ControllerDateCreated;
  int _ControllerId;

  Controller(this._ControllerName, this._ControllerNumber, this._ControllerDateCreated);

  Controller.map(dynamic obj){
    this._ControllerName = obj['ControllerName'];
    this._ControllerNumber = obj['ControllerNumber'];
    this._ControllerDateCreated = obj['ControllerDateCreated'];
    this._ControllerId = obj['ControllerId'];
  }

  String get ControllerName => _ControllerName;
  String get ControllerNumber => _ControllerNumber;
  String get ControllerDateCreated => _ControllerDateCreated;
  int get ControllerId => _ControllerId;

  Map<String, dynamic> toMap(){
    var map = new Map<String, dynamic>();
    map["ControllerName"] = _ControllerName;
    map["ControllerNumber"] = _ControllerNumber;
    map["ControllerDateCreated"] = _ControllerDateCreated;

    if(_ControllerId != null){
      map["ControllerId"] = _ControllerId;
    }
    return map;
  }

  Controller.fromMap(Map<String, dynamic> map){
    this._ControllerName = map["ControllerName"];
    this._ControllerNumber = map["ControllerNumber"];
    this._ControllerDateCreated = map["ControllerDateCreated"];
    this._ControllerId = map["ControllerId"];
    }

  @override
  Widget build(BuildContext context) {
    return new
    ListTile(
      leading: new CircleAvatar(
        backgroundColor: Colors.cyan,
        child: new Text(
          _ControllerName[0],
          //"V",
          style: new TextStyle(color: Colors.black),
        ),
      ),
      title: new Text(_ControllerName, style: TextStyle(
          color: Colors.white, fontWeight: FontWeight.bold
      ),),
      subtitle: new Text(_ControllerNumber, style: TextStyle(
          color: Colors.white, fontStyle: FontStyle.italic
      ),),

    );
  }
}


//Second Screen

class ContainerHome extends StatefulWidget {
  @override
  _ContainerHomeState createState() => _ContainerHomeState();
}

class _ContainerHomeState extends State<ContainerHome> {

  var db = DatabaseHelper();

  final _textEditingControllerName = new TextEditingController();
  final _textEditingControllerNumber = new TextEditingController();
  final _formKey = new GlobalKey<FormState>();
  final List<Controller> _itemList = <Controller>[];
  //List widgets = [];

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

  // Save the data to database
  void _handelSubmitted(String controllerName, String controllerNumber) async{
    Controller controller = new Controller(controllerName, controllerNumber, DateTime.now().toIso8601String());
    int savedItemId = await db.saveController(controller);
    Controller addedItem = await db.getItem(savedItemId);

    setState(() {
      _itemList.insert(0, addedItem);
    });

    print("Item saved id $savedItemId");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        reverse: false,
          itemCount: _itemList.length,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              color: Colors.black.withOpacity(0.6),
              child: new ListTile(
                title: _itemList[index],
                onLongPress: () => {},
                    //_updateItem(context, _itemList[index], index),
                trailing: new Listener(
                  key: new Key(_itemList[index].ControllerName),
                  child: new Icon(
                    Icons.delete,
                    color: Colors.redAccent,
                  ),
                  onPointerDown: (pointerEvent) => {},
                      //_deleteToDo(_itemList[index].id, index),
                ),
              ),
            );   //getRow(index);
          }),
        floatingActionButton: new FloatingActionButton(
            onPressed: () {
              _showFormDialog();
              /*showDialog(
                  context: context,
                  builder: (_) => new SimpleDialog(
                    title: new Text("Add Controler"),
                    children: <Widget>[
                      Padding(
                          padding:
                          const EdgeInsets.symmetric(horizontal: 14.0),
                          child: Column(
                            children: <Widget>[
                              TextFormField(
                                controller: _textEditingControllerName,
                                validator: (val) => val.length == 0 ? "Enter Controller name": null,
                                //onSaved: (val) => this._ControllerName = val,
                                decoration: InputDecoration(
                                  labelText: "Name",
                                ),
                              ),
                              TextFormField(
                                controller: _textEditingControllerNumber,
                                validator: (val) => val.length == 0 ? "Enter Controller number": null,
                                //onSaved: (val) => _ControllerNumber = val,
                                decoration: InputDecoration(
                                  labelText: "Number",
                                ),
                                keyboardType: TextInputType.number,
                              ),
                              Row(
                                children: <Widget>[
                                  Padding(
                                    padding:
                                    const EdgeInsets.only(left: 18.0),
                                    child: Center(
                                      child: RawMaterialButton(
                                        onPressed: () {
                                          _handelSubmitted(_textEditingControllerName.text, _textEditingControllerNumber.text);
                                          _textEditingControllerName.clear();
                                          _textEditingControllerNumber.clear();
                                        },
                                        fillColor: Colors.indigo,
                                        splashColor: Colors.white,
                                        child: Padding(
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 6.0),
                                          child: Text(
                                            "SUBMIT",
                                            style: TextStyle(
                                                color: Colors.white),
                                          ),
                                        ),
                                        shape: const StadiumBorder(),
                                      ),
                                    ),
                                  ),
                                  SizedBox(
                                    width: 22.0,
                                  ),
                                  RawMaterialButton(
                                    onPressed: () => Navigator.pop(context),
                                    fillColor: Colors.deepOrange,
                                    splashColor: Colors.white,
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                          horizontal: 6.0),
                                      child: Text(
                                        "CANCEL",
                                        style:
                                        TextStyle(color: Colors.white),
                                      ),
                                    ),
                                    shape: const StadiumBorder(),
                                  ),
                                ],
                              )
                            ],
                          ))
                    ],
                  ));*/
            },
            tooltip: "Add Controler",
            child: Icon(Icons.add))
    );
  }

  void _showFormDialog() {
    var alert = new AlertDialog(
      title: Text("Add new Controller"),
      content: Row(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          new Expanded(
            child:
                Form(
                  key: _formKey,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      new TextFormField(
                        keyboardType: TextInputType.text,
                        controller: _textEditingControllerName,
                        validator: (value) {
                          if (value.isEmpty) {
                            return "Please enter your task";
                          }
                        },
                        autofocus: true,
                        decoration: new InputDecoration(
                            labelText: "Controller Name",
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(
                                  const Radius.circular(0.0),
                                )),),
                      ),
                      SizedBox.fromSize(
                        size: Size(0.0, 10.0),
                      ),
                      new TextFormField(
                        //keyboardType: TextInputType.number,
                        controller: _textEditingControllerNumber,
                        validator: (value) {
                          if (value.isEmpty) {
                            return "Please enter your task";
                          }
                        },
                        autofocus: true,
                        decoration: new InputDecoration(
                          labelText: "Controller Number",
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                const Radius.circular(0.0),
                              )),),
                      ),
                    ],
                  ),
                ),

          )
        ],
      ),
      actions: <Widget>[
        new OutlineButton(
            onPressed: () {
                _handelSubmitted(_textEditingControllerName.text, _textEditingControllerNumber.text);
                _textEditingControllerName.clear();
                _textEditingControllerNumber.clear();

            },
            borderSide: BorderSide(color: Colors.green),
            child: Text("Save")),
        new OutlineButton(
            onPressed: () {
                Navigator.pop(context);
            },
            borderSide: BorderSide(color: Colors.red),
            child: Text("Cancel"))
      ],
    );
    showDialog(
        context: context,
        builder: (_) {
          return alert;
        });
  }

// Retrive the data from database
  _controllerList() async{
    List items = await db.getItems();
    items.forEach((item){
      Controller controller = Controller.fromMap(item);
      print("DB Items ${controller.ControllerName}");
      print("DB Items ${controller.ControllerNumber}");
      print("DB Items ${controller.ControllerId}");
    });

  }

}

0 个答案:

没有答案