如何在flutter中动态设置state变量?

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

我刚刚开始学习颤动,我很好奇我怎么能动态地挥动setState()

React Native我通常动态地使用这样的函数来setState

class foo extends React.Component{
  state={
    username:null,
    password:null
  }

  toggleSetState(whatState, value){
    this.setState({ [whatState]: value })
  }

  render() {
    return (
      <View>
        <TextInput
          value={this.state.username}
          onChangeText={(text)=>{toggleSetState(username, text)}
        />
        <TextInput
          value={this.state.password}
          onChangeText={(text)=>{toggleSetState(password, text)}
        />
      </View>
    );
  }
}

什么是Flutter上面代码的等价物?

我在Flutter尝试了这个,但它似乎不起作用

class _LoginFormState extends State<LoginForm> {
  String username, password;

  void ToogleState(typedata, text){
    setState(() {
      typedata = text;
    });
  }

  //Widget
  TextField(
    onChanged: (text){ToogleState(username, text); print(username);},
    decoration: InputDecoration(
      hintText: 'input username', labelText: 'Username'
    ),
  ),
}
dart flutter
3个回答
0
投票
setState(() { _myState = newValue });

_myState是可变的


0
投票

您只需要创建一个变量来保存该值。当你没有修改短暂状态时,我很困惑你为什么要调用setState

这里有一些有用的文档https://flutter.dev/docs/development/data-and-backend/state-mgmt/ephemeral-vs-app

class _LoginFormState extends State<LoginForm> {
  String _username = "";
  String __password = "";
  void ToogleState( text){
    setState(() {
      _username = text;
    });
  }

  //Widget
  TextField(
    onChanged: (text){ToogleState( text); print(username);},
    decoration: InputDecoration(
      hintText: 'input username', labelText: 'Username'
    ),
  ),
}

0
投票

经过一些研究和尝试,我可以用下面的代码实现我想要的:

class _LoginFormState extends State<LoginForm> {
  String username, password;
  //create an object
  var loginForm = {};
  final myController = TextEditingController();

  void ToogleState(typedata, text){
    setState(() {
      //i can assign any different variable with this code
      loginForm[typedata] = text;
      //output of LoginForm: {username: foo, password: bar}
    });
  }

  //widget
  Padding(
    padding: const EdgeInsets.all(16.0),
    child: Column(
      children: <Widget>[
        TextField(
          onEditingComplete: (){print(loginForm);},
          onChanged: (text){ToogleState("username", text); print(loginForm['username']);},
          decoration: InputDecoration(
            hintText: 'input username', labelText: 'Username'
          ),
        ),
        TextField(
          onEditingComplete: (){print(loginForm);},
          onChanged: (text){ToogleState("password", text); print(loginForm['password']);},
          decoration: InputDecoration(
            hintText: 'input password', labelText: 'Password'
          ),
        ),
      ],
    ),
  );
}
© www.soinside.com 2019 - 2024. All rights reserved.