在 flutter 中使用 AlertDialog 显示数据库中的选定数据

Display selected data from database using AlertDialog in flutter

Hi im trying to display the specific or selected data from database using alert dialog however the data i want to display doesn't display to alertDialog by the way im using floor for my database im pretty stack on this any suggestion or idea will be well appreciated.

这是我的代码

Widget buildAboutDialog(BuildContext context,
      AddContactCallback _contactscreen, bool isEdit, ContactObject _contactObject)  {
      final databases = $FloorContactDatabase.databaseBuilder('Contacts.cb').build();
      if(contactObject != null) {
        this.contactObject = _contactObject;
        tfirstname.text = _contactObject.firstname;
        tlastname.text = _contactObject.lastname;
        tbirthday.text = _contactObject.birthday;
        tcontactnumber = _contactObject.contactnumber as TextEditingController ;
        tprofilepicture = _contactObject.profilepicture as File;
      } else {
        print('ERROR');
        print(tfirstname.value);
      }
      return new AlertDialog(
        title: new Text(isEdit ? 'Contact!' : 'Contact'),
        content: new SingleChildScrollView(
          child: new Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              SizedBox(
              height: 10.0,
              ),
              Align(
                alignment: Alignment.center,
                child: CircleAvatar(
                radius: 70,
                backgroundColor: Color(0xff476cfb),
                child: ClipOval(
                  child: new SizedBox(
                    width: 180.0,
                    height: 180.0,
                    child: (_image != null) ? Image.file(_image, // Image.file(File('${_contactsDao.profilepicture}'),
                      fit: BoxFit.fill,
                    ) : Image.network(
                      "https://images.unsplash.com/photo-1502164980785-f8aa41d53611?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
              ),
              ),
              getTextFieled("First Name", tfirstname),
              getTextFieled("Last Name", tlastname),
              getTextFieled("Birth day", tbirthday),
              getTextFieled("Contact No", tcontactnumber),
            ],
          ),
        ),
      );
  }

这里是函数和实例

    Widget getTextFieled(
      String inputData, TextEditingController inputTextController) {
      var btm = new Padding(
          padding: const EdgeInsets.all(5.0),
          child:  new  TextFormField(
            controller: inputTextController,
            decoration: new InputDecoration(
              hintText: inputData,
            ),
          ),
        );
      return btm;
 }

 Widget getAppButton (String buttonLabel, EdgeInsets margin){
    var btm = new Container(
      margin: margin,
      padding: EdgeInsets.all(8.0),
      alignment: FractionalOffset.center,
      decoration: new BoxDecoration(
        border: Border.all(color: const Color(0xFF28324E)),
        borderRadius: new BorderRadius.all(const Radius.circular(6.0)),
      ),
      child: new Text(
          buttonLabel,
          style: new TextStyle(
            color: const Color(0xFF28324E),
            fontSize: 20.0,
            fontWeight: FontWeight.w300,
            letterSpacing: 0.3,
          ),
      ),
    );
    return btm;
 }

 ContactObject getdata(bool isEdit) {
    return new ContactObject(
      firstname: tfirstname.text,
     lastname: tfirstname.text,
     birthday: tbirthday.text,
     contactnumber: int.parse(tcontactnumber.text),
      profilepicture: tprofilepicture.readAsStringSync(),
    );
 }

 onTap(bool isEdit, AddContactCallback addContactCallback, BuildContext context) {
    if(isEdit) {
      addContactCallback.updateContacts(getdata(isEdit));
      Navigator.of(context).pop();
      print('ANG PUMASOK');
      print(tfirstname);
    } else {
      Fluttertoast.showToast(
          msg: 'ERROR ERROR',
          toastLength: Toast.LENGTH_SHORT,
          timeInSecForIosWeb: 1,
          gravity: ToastGravity.BOTTOM
      );
    }
 }


}

abstract class AddContactCallback {
    void updateContacts(ContactObject contactObject);
}

这是我的想法的截图

我认为设置TextEditingController后需要将值设置为TextFormField
在返回小部件之前尝试,设置一个值;

Widget getTextFieled(
      String inputData, TextEditingController inputTextController) {
      var btm = new Padding(
          padding: const EdgeInsets.all(5.0),
          child:  new  TextFormField(
            controller: inputTextController,
            decoration: new InputDecoration(
              hintText: inputData,
            ),
         ),
      );
      inputTextController.text = "Some Value Test";
      return btm;
 }

长期使用此方法来修改列表或其他中的项目。

此代码只是其工作原理的示例。

在基本小部件中写下:

class BaseWidget extends StatefulWidget {
  @override
  _BaseWidgetState createState() => new _BaseWidgetState();
}

class _BaseWidgetState extends State<BaseWidget> {
  @override
  void initState() {
    // get data from data base
    _getDataFromDataBase();
    super.initState();
  }

  var _listComingDataFromDataBase;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _listComingDataFromDataBase == null
          ? Container(
              width: 50,
              height: 50,
              child: CircularProgressIndicator(),
            )
          : RefreshIndicator(
              onRefresh: () async {
                _getDataFromDataBase();
              },
              child: ListView.builder(
                itemBuilder: (context, index) {
                  return InkWell(
                    child: Container(
                      height: 100,
                    ),
                    onTap: () {
                      _buildAlertDialog(
                          context,
                          _listComingDataFromDataBase[
                              index]); //open dialog and send selected object
                    },
                  );
                },
                itemCount: _listComingDataFromDataBase.length,
              ),
            ),
    );
  }

  void _buildAlertDialog(context, selectedObject) {
    showDialog(
        context: context,
        child: AlertDialog(
          content: EditObjectWidget(selectedObject),
        )).then((isEdited) {
      if (isEdited) {
        // you can reload data from database
        _getDataFromDataBase();
      }
    });
  }

  void _getDataFromDataBase() {
    // database.getData.then((data){setState(){_listComingDataFromDataBase = data};});
  }
}

创建 EditObjectWidget 像这样:

class EditObjectWidget extends StatefulWidget {
  final selectedObject;

  EditObjectWidget(this.selectedObject);

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

class _EditObjectWidgetState extends State<EditObjectWidget> {
  final TextEditingController _firstNameController = TextEditingController();
  final TextEditingController _numberController = TextEditingController();

  @override
  void initState() {
    fillFields(widget.selectedObject);
    super.initState();
  }

  void fillFields(selectedObject) {
    _firstNameController.text = selectedObject.fistName ?? '';
    if (selectedObject.number != null)
      _numberController.text = selectedObject.number.toString();
  }

  @override
  void dispose() {
    _firstNameController.dispose();
    _numberController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        TextField(
          controller: _firstNameController,
        ),
        TextField(
          controller: _numberController,
          keyboardType: TextInputType.number,
        ),
        RaisedButton(
          onPressed: () {
            _updateObject();
          },
          child: Text('Submit'),
        )
      ],
    );
  }

  void _updateObject() {
    //update object in data base
    // database.updateObject({'number':_numberController.text,'first_name':_firstNameController.text});
    //if updateObject method return true, close dialog with true result, Otherwise false
    bool isEdited = true;
    if(!isEdited)
    {
      //show validation error, or another
    }
    else
    Navigator.pop(context, isEdited);
  }
}

我没有使用你的代码,只是解释一下

希望这段代码对您有所帮助