【发布时间】:2019-12-10 14:53:06
【问题描述】:
我正在为我在 Flutter 工作的公司构建一个应用程序。我们正在与我合作的其他开发人员一起使用 MVVM(模型、视图、视图模型)架构。
我想将用户数据从我的 ViewModel 显示到我的编辑表单(这些数据是通过我们的 API 获取的)。
问题是:数据不会显示在我的视图中。我可以访问它,我可以打印它(见下面的截图)......
到目前为止我尝试了什么:
- 我主要使用了 initialValue 并调用了例如我的“lastName”变量(但它没有显示任何内容)
- 我尝试为每个字段使用一个控制器。使用这种方法,它会显示我的用户数据,但是我遇到了一个奇怪的键盘问题,每次我想输入一些内容时,光标都会转到开头并删除单词。
另外,我注意到我的变量可以显示在 Text() 小部件中。
我很无知,我真的很想得到这个错误的答案。
class MyAccountViewModel with ChangeNotifier {
String _lastName;
MyAccountViewModel() {
// this._lastName = 'Hardcoded text';
ApiHelper api = new ApiHelper();
api.getUserData().then((Map<String, dynamic>response) {
print(response);
this._lastName = response['last_name'];
});
notifyListeners();
}
String get lastName => this._lastName;
set lastName(String value) {
this._lastName = value;
notifyListeners();
}
Widget editProfileForm(model, BuildContext context) {
return Form(
key: _formKey,
child: Column(
children: <Widget>[
TextFormField(
initialValue: model.lastName,
),
],
),
);
}
【问题讨论】:
-
我可以看看你的
Form小部件源代码吗? -
@Metr0me,为了快速准确的响应,您需要包含一个基本的可运行代码,说明您正在做什么,否则只是猜测。
-
我简化了我的代码,以便您更好地理解:)