Reputation: 1984
I just start to learn flutter, and I'm curious about how can i setState()
dynamically in flutter
in React Native
i usually used a function like this to setState
dynamically:
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>
);
}
}
what is an equivalent of above code in Flutter
?
I've tried this in Flutter
but it seems doesn't work
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'
),
),
}
Upvotes: 3
Views: 8121
Reputation: 1984
after some research and trying, i can achieve what i want with the code below:
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'
),
),
],
),
);
}
Upvotes: 5
Reputation: 8202
You just need to make a variable to hold the value. I am confused why you are calling setState when you are not modifying ephemeral state
Here are some helpful docs 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'
),
),
}
Upvotes: 2