Created with <3 with dartpad.dev.
Created
May 17, 2023 01:55
-
-
Save hongsw/6a88a2528d338a3795f6b7263ea0886c to your computer and use it in GitHub Desktop.
입력값을 클래스의 속성에 적용하는 예시
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class UserProfile { | |
String email; | |
String password; | |
UserProfile({required this.password, required this.email}); | |
static String? emailValidator(String? value) { | |
if (value == null || value.isEmpty) { | |
return 'Please enter your email'; | |
} | |
return null; | |
} | |
static String? passwordValidator(String? value) { | |
if (value == null || value.isEmpty) { | |
return 'Please enter your password'; | |
} | |
return null; | |
} | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Form Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: MyHomePage(), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
_MyHomePage createState() => _MyHomePage(); | |
} | |
class _MyHomePage extends State<MyHomePage> { | |
UserProfile user = UserProfile(email: "", password: ""); | |
final _formKey = GlobalKey<FormState>(); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text('Flutter Form Demo Home Page'), | |
), | |
body: Form( | |
key: _formKey, | |
child: Column( | |
children: <Widget>[ | |
TextFormField( | |
decoration: const InputDecoration( | |
hintText: 'Enter your email', | |
), | |
validator: (value) { | |
return UserProfile.emailValidator(value); | |
}, | |
onSaved: (value) { | |
// Save the email value | |
setState(() { | |
user.email = value!; | |
}); | |
}, | |
), | |
TextFormField( | |
decoration: const InputDecoration( | |
hintText: 'Enter your password', | |
), | |
validator: (value) { | |
return UserProfile.passwordValidator(value); | |
}, | |
onSaved: (value) { | |
// Save the password value | |
setState(() { | |
user.password = value!; | |
}); | |
}, | |
), | |
ElevatedButton( | |
onPressed: () { | |
if (_formKey.currentState!.validate()) { | |
print("after validate : ${user.email} "); | |
_formKey.currentState!.save(); | |
print("after save : ${user.email} "); | |
// If the form is valid, display a Snackbar. | |
ScaffoldMessenger.of(context) | |
.showSnackBar(SnackBar(content: Text('Processing Data'))); | |
} | |
}, | |
child: Text('Submit'), | |
), | |
Text("user.email : ${user.email}"), | |
Text("user.password : ${user.password}") | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment