Flutter перестраивается после открытия/закрытия клавиатурыAndroid

Форум для тех, кто программирует под Android
Anonymous
Flutter перестраивается после открытия/закрытия клавиатуры

Сообщение Anonymous »

В настоящее время я работаю над обновлением профиля приложения, но, похоже, возникла проблема. Проблема в том, что когда мы хотим перейти на страницу, мы хотим увидеть текстовое поле, загруженное с использованием предыдущих данных или старых данных. Для этого мы используем построитель будущего, чтобы получить данные, а затем установить их в поле. Но когда мы используем клавиатуру на мобильных устройствах для нажатия и редактирования текстовых полей, происходит следующее: будущий конструктор снова перестраивается только потому, что сборка вызывается из-за этого изменения размера экрана, когда клавиатура поднимается и опускается. Чтобы исправить это, мне нужно было создать временную будущую переменную, и она обновляется только в том случае, если она равна нулю. Кроме того, текстовое поле обновляется только в том случае, если счетчик равен определенному значению IE, в данном случае одному, но это не работает. Мы хотим размещать текст в текстовом поле каждый раз, когда мы переходим на обновление страницы или нажимаем кнопку «Отправить». Вот здесь у меня какие-то проблемы. Я пробовал использовать состояния и получаю тот же результат, возможно, я его неправильно настраиваю.
Цель: загрузить данные, установить текстовые поля с данными, которые я только что получил, отредактировать их как Они мне нужны (данные остаются неизменными при подъеме или опускании клавиатуры). Затем обновите эти данные с помощью кнопки обновления.

old:
class Test extends StatelessWidget {

Future getFuture() async {
_profile = await HTTP.getProfile();
}

Widget build(BuildContext context) {
return FutureBuilder(
future: getFuture(); // generate every time
builder: () {
return nameFeild();
}
)
}

Widget nameFeild(){
_changeNameController.text = _profile.name;
return TextField(controller: _nameController);
}
}

new:
class Test extends StatelessWidget {
Future testFuture;
static int count = 0;
Future getFuture() async {
_profile = await HTTP.getProfile();
}

Widget build(BuildContext context) {
testFuture ??= getFuture();
count++;
return FutureBuilder(
future: testFuture; // generate every time
builder: () {
return nameFeild();
}
)
}

Widget nameFeild(){
if(count == 1){
_changeNameController.text = _profile.name;
}
return TextField(controller: _nameController);
}
}

Фактический код
// imports

class UserSettingPage extends StatelessWidget {
BuildContext context;
GetSizes _sizes;
double _w;
double _h;
NavbarWidget _navBar = NavbarWidget();
FooterWidget _footer = FooterWidget.autoPosition();
ImageProvider _userPicture =
AssetImage('assets/images/team/zain.png'); //Defaultpic.png');
Cookies _cookies = Cookies();

final _oldPasswordControllerOne = TextEditingController();
final _resetPasswordControllerOne = TextEditingController();
final _resetPasswordControllerTwo = TextEditingController();

final _changeNameController = TextEditingController();
final _changeBioController = TextEditingController();
final _changeNumberController = TextEditingController();

final _changeFacebookController = TextEditingController();
final _changeTwitterController = TextEditingController();
final _changeInstagramController = TextEditingController();

CheckBoxValueNotifier email = new CheckBoxValueNotifier(false);
CheckBoxValueNotifier phone = new CheckBoxValueNotifier(false);

bool _isDesktop;
Authentication _authentication = Authentication();
Encryption _encryption = Encryption();
DialogBox _dialog = DialogBox();
passwordValidNotifier passwordNotifier = new passwordValidNotifier();
ProfileModel _user;
Uint8List _base64;

bool phoneCheckedValue = false;
bool emailCheckedValue = false;
String userID;
FilePickerWidget imagePicker = FilePickerWidget();
Future _getUser;
static int count = 0;

Future retrieveUser() async {
userID = await Cookies.getCookieValue("userID");
await DioCalls.getProfile(context, userID).then((value) => _user = value);
}

@override
Widget build(BuildContext context) {
this.context = context;
_sizes = GetSizes(context);
_w = _sizes.getPageWidth();
_h = _sizes.getPageHeight();
_isDesktop = _sizes.isDesktop();
print('Update Data: ' + (_getUser == null).toString() + ' count: ' + count.toString());
_getUser ??= retrieveUser();
count++;
return LayoutBuilder(builder: (context, constraints) {
if (_sizes.isDesktop()) {
return _bigDisplay();
} else {
return _smallDisplay();
}
});
}

Widget _bigDisplay() {
// code
}

Widget _smallDisplay() {
return FutureBuilder(
future: _getUser,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: Text(''));
} else {
if (snapshot.hasError) {
return Center(child: Text('Errors: ${snapshot.error}'));
} else {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
children: [
_navBar,
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [userPictureAndBorder()],
),
userInfo(),
line(),
changeNameTile(),
line(),
changeBioTile(),
line(),
changeSocialMediaTile(),
line(),
changeNotificationTile(),
line(),
changePasswordTile(),
line(),
Container(
margin: EdgeInsets.fromLTRB(0, 10, 0, 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [logoutButton(), updateButton(context)],
),
)
],
),
),
)
],
),
);
}
}
},
);
}

// OTHER WIDGETS CODE WERE REMOVED, I dont think you need them

Widget userInfo() {
return Container(
margin: EdgeInsets.fromLTRB(0, 5, 0, 10),
alignment: Alignment.center,
child: Column(
children: [
SelectableText(
_user.userID,
style: TextStyle(
fontWeight: FontWeight.w800,
fontSize: 14,
color: Colors.black,
// height: 21,
),
),
SelectableText(
_user.name,
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 14,
color: Colors.black,
// height: 21,
),
),
SelectableText(
'732-318-5555 (change)',
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 14,
color: Colors.black,
// height: 21,
),
),
],
),
);
}

Widget logoutButton() {
return ElevatedButton.icon(
onPressed: () {
print('Logging out');
},
icon: Icon(Icons.logout),
label: Text("Logout"),
style: ElevatedButton.styleFrom(
primary: Colors.black, // background
onPrimary: Colors.white, // foreground
),
);
}

Widget updateButton(BuildContext context) {
return ElevatedButton.icon(
onPressed: () async {
_user.name = _changeNameController.text;
_user.bio = _changeBioController.text;
_user.socialMedia.Facebook = _changeFacebookController.text;
_user.socialMedia.Instagram = _changeInstagramController.text;
_user.socialMedia.Twitter = _changeTwitterController.text;

DioCalls.updateProfile(context, _user, imagePicker.selectedFile,
await Cookies.getCookieValue("jwt"));
Navigator.pop(context); // pop current page
Navigator.pushNamed(context, "/test1"); // push it back in
_oldPasswordControllerOne.clear();
_changeBioController.clear();
count = 0;
_getUser = null;
},
icon: Icon(Icons.update),
label: Text("Update"),
style: ElevatedButton.styleFrom(
primary: Colors.black, // background
onPrimary: Colors.white, // foreground
),
);
}

Widget nameTextField() {
return SelectableText(
"Edit Name",
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 16,
fontStyle: FontStyle.normal,
fontFamily: 'Poppins-Black',
fontWeight: FontWeight.w500,
),
);
}

Widget bioTextField() {
return SelectableText(
"Edit Bio (Max: 100)",
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 16,
fontStyle: FontStyle.normal,
fontFamily: 'Poppins-Black',
fontWeight: FontWeight.w500,
),
);
}

Widget changeNameTile() {
if (count == 1) {
print('updating text');
_changeNameController.text = _user.name;
}
return ExpansionTile(
title: Text(
'Name',
style: TextStyle(
fontSize: (_sizes.isDesktop()) ? 16 : 12,
fontWeight: FontWeight.w500,
color: Colors.black),
textAlign: TextAlign.left,
),
children: [
nameTextField(),
Container(
margin: EdgeInsets.all(20),
child: Theme(
data: ThemeData(
primaryColor: Colors.transparent,
hintColor: Colors.transparent),
child: TextField(
maxLength: 50,
controller: _changeNameController,
decoration: InputDecoration(
counterText: '',
contentPadding: EdgeInsets.all(20.0),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(),
borderRadius: BorderRadius.all(Radius.circular(
10) //

Подробнее здесь: https://stackoverflow.com/questions/666 ... ens-closes

Вернуться в «Android»