7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

package:provider を使ったFormのValidationのサンプル

7
Posted at

画面構成

画面の構成的には、containerとなるページがあり、その上にログイン画面が表示されるような構成を想定しています。

main
 └ container
     └ login

main.dart

ChangeNotifierProvider をつかって状態オブジェクトを配置する。

main.dart
void main() =>
    runApp(
        MultiProvider(
          providers: [
            ChangeNotifierProvider(create: (context) => ContainerStore()),
            ChangeNotifierProvider(create: (context) => LoginStore()),
          ],
          child: App(),
        )

    );

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
      home: Container(),
    );
  }
}

コンテナページの作成

特に作る必要もないですが、ログインページはdismissされるというそうていで一応配備します。
ログインページを表示するだけ。

container.dart
class Container extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Login();
  }
}

class ContainerStore with ChangeNotifier {
}

ログインページの作成

TextFormFieldonChange: イベントで毎回メールアドレスのチェックを行い、エラーがある場合はメアド入力欄の下にエラーメッセージを表示しています。エラーの通知は notifyListeners() で行っています。

login.dart
class Login extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer <LoginStore>(
        builder: (context, loginStore, _) {
          return Scaffold(
              backgroundColor: Colors.blue[300],
              body: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  SizedBox(height: 50),
                  TextFormField(
                    onChanged: (text) => loginStore.changeEmail(text),
                  ),
                  Text('${loginStore.emailError}'), // エラーメッセージ
                ],
              )
          );
        });
  }
}

class LoginStore with ChangeNotifier {
  var email = "";
  var emailError = "";

  void changeEmail(String text) {
    email = text;
    emailError = validate() ? "" : "メールアドレスを正しく入力してください";
    notifyListeners();
  }
  bool validate(String email) {
    // validation処理を書く
  }
}
7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?