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

fli*_*lix 3 dart flutter

我刚刚开始学习flutter,我很好奇如何setState()动态地在flutter中

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

与上面的代码等效的是什么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'
    ),
  ),
}
Run Code Online (Sandbox Code Playgroud)

fli*_*lix 5

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

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'
          ),
        ),
      ],
    ),
  );
}
Run Code Online (Sandbox Code Playgroud)