我正在为应用程序开发用户配置文件更新页面,我在那里遇到问题,用初始数据填充表单我使用StreamBuilder
并使用TextEditingController
加载数据到TextField
,数据加载正常并且运行良好,但问题是当我尝试更改TextField
时并专注于下一个TextField
StreamBuilder
刷新ui与tha数据加载以前和丢失编辑数据。在这种情况下,Stream不会从网络呼叫更新。有人遇到过这种情况吗?或任何推荐的方式来做到这一点?请帮忙。
码
class UserProfileScreen extends StatefulWidget {
@override
_UserProfileScreenState createState() => _UserProfileScreenState();
}
class _UserProfileScreenState extends State<UserProfileScreen> {
UserProfileBloc userBloc;
final firstNameController = TextEditingController();
final surnameNameController = TextEditingController();
final phoneController = TextEditingController();
final emailController = TextEditingController();
var _hashCode = 0;
@override
void initState() {
super.initState();
userBloc = UserProfileBloc();
userBloc.getUser();
}
@override
void dispose() {
userBloc.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
leading: IconButton(
icon: Icon(
Icons.close,
color: ColorPallet.white,
),
onPressed: () {
if (Navigator.canPop(context)) {
Navigator.pop(context);
}
},
)
),
body: buildUserProfileContent(context),
);
}
Container buildUserProfileContent(BuildContext context) {
return Container(
child: StreamBuilder<UserProfileState>(
stream: userBloc.user,
initialData: UserProfileInitState(),
builder: (context, snapshot) {
if (snapshot.data is UserProfileDataState) {
UserProfileDataState state = snapshot.data;
return buildProfileContent(state.user, state.profileImage);
}
},
),
);
//);
}
ListView buildProfileContent(User user, Uint8List profileImage) {
firstNameController.text = user.firstName;
return ListView(
children: <Widget>[
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextField(
controller: firstNameController,
),
]
),
)],
);
}
}
在构建方法中设置值时会出现此问题。如果你想像上面那样设置值,那么在类_UserProfileScreenState
中保持一个变量_initialized = false
并在初始化后使其成为true
。
就像是:
if(!_initialized){
firstNameController.text = user.firstName;
_initialized = true;
}
希望这可以帮助!