StreamBuilder中的TextField丢失了已编辑的值

问题描述 投票:0回答:1

我正在为应用程序开发用户配置文件更新页面,我在那里遇到问题,用初始数据填充表单我使用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,
              ),
            ]

        ),
        )],
    );
  }
}
flutter textfield flutter-layout
1个回答
0
投票

在构建方法中设置值时会出现此问题。如果你想像上面那样设置值,那么在类_UserProfileScreenState中保持一个变量_initialized = false并在初始化后使其成为true

就像是:

if(!_initialized){
    firstNameController.text = user.firstName;
    _initialized = true;
}

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.