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

标签 dart flutter

我刚开始学习flutter,很好奇如何在flutter中动态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'
    ),
  ),
}

最佳答案

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

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'
          ),
        ),
      ],
    ),
  );
}

关于dart - 如何在flutter中动态设置State变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55604751/

相关文章:

flutter - 什么是 MaterialStateProperty<OutlinedBorder>

flutter - 从无状态小部件调用到有状态小部件时,变量返回null吗?

dart - 等待直到另一个异步函数完成

google-cloud-firestore - 使用 Flutter 和 Firestore 显示某些数据

image - 如何在不使用 go-flutter 的情况下在 flutter 桌面中使用 image_picker 插件

dialog - 如何关闭 flutter 对话框?

dart - 在 Flutter 的 ListViewBuilder 中使用动态 TextField

dart - 是否将大型应用程序作为单个web_ui应用程序使用?

dart - 如何使用RPC处理Dart lang中 “hub.challenge”形式的查询参数?

firebase - Firestore 中的 getDocuments() 和 snapshots() 有什么区别?