简体   繁体   中英

Flutter TextFormfield Controller get value

This is Textformfield. It receives the value and then displays the information through it. TextEditContoller

This is page 1

 Widget lngTextFormField(String label, String keyword, String text) {
TextEditingController lngtextController = TextEditingController(text: text);
lngtextController.selection = TextSelection.collapsed(offset: lngtextController.text.length);
return TextFormField(
  controller: lngtextController,
  onChanged: (value) {
    saveAd(value, keyword);
  },
  decoration: InputDecoration(
    labelText: label,
    labelStyle: TextStyle(
      fontFamily: 'supermarket',
      fontSize: 16,
    ),
    isDense: true,
  ),
);
}

This is a page 2 This is a save button that will return lat,lng to page 1.

void saveAddress() {
var lat = centerMap.latitude;
var lng = centerMap.longitude;
Navigator.push(
  context,
  MaterialPageRoute(
    builder: (context) => EditAddressPage(
      index: widget.index,
      lat: lat.toString(),
      lng: lng.toString(),
    ),
  ),
);
print("Saving address: Latitude: $lat, Longitude: $lng");
}

what can i do I want to send the second page lat,lng values back to page 1 instead of the existing values. I tried this, sometimes the value is sent but the original value is empty before the new value is sent. Maybe need to type something in TextFormfield before being able to save

There are a lot of option to do, but the one of the easiest is:

  • When navigates to 2nd page from 1st page, replace or pop it

//you can use this

Navigator.pushReplacement(context, route); 

//or this

Navigator.of(context).push(MaterialPageRoute(builder: (context) => NewScreen()));

Navigator.pop(context);
  • after 2nd page open and button pressed, you need to pass string to 1st page using Navigator.push (you have done it well)

  • inside initstate of the 1st page make a condition, example

    @override void initState() { super.initState(); if (widget.lat.= null || widget.lat.= "") { lattextController;text = widget.lat.. } if (widget.lng;= null || widget,lng != "") { lngtextController.text = widget.lng!; } //sometime when initsate doesnt work you can call setstate, depends on logic that you writes }

this logic means that when the 1st page created they will set the value first before build()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM