Created with <3 with dartpad.dev.
Last active
May 17, 2023 00:35
-
-
Save hongsw/a81242c3effa19d0b503d0a6d9509b4d 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(title: 'Flutter Form Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
MyHomePage({Key? key, required this.title}) : super(key: key); | |
final String title; | |
final _formKey = GlobalKey<FormState>(); | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
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 | |
}, | |
), | |
TextFormField( | |
decoration: const InputDecoration( | |
hintText: 'Enter your password', | |
), | |
validator: (value) { | |
return UserProfile.passwordValidator(value); | |
}, | |
onSaved: (value) { | |
// Save the password value | |
}, | |
), | |
ElevatedButton( | |
onPressed: () { | |
if (_formKey.currentState!.validate()) { | |
_formKey.currentState!.save(); | |
// If the form is valid, display a Snackbar. | |
ScaffoldMessenger.of(context) | |
.showSnackBar(SnackBar(content: Text('Processing Data'))); | |
} | |
}, | |
child: Text('Submit'), | |
), | |
], | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment