LoginSignup
1
0

Dartのgetとは?

Posted at

引数が必要ないメソッド?

Dartのゲッターは、引数を取らないメソッドのようなものです。ゲッターは、インスタンス変数の値を取得するために使用され、メソッドのように呼び出されることはありません。

ゲッターの定義方法は2つあります:

アロー構文 (=>を使用):

String get timeCheck => now == time ? '同じ時間' : '違う時間';

ブロック構文 (return文を使用):

String get timeChecker {
  if (now == time) {
    return '同じ時間';
  } else {
    return '違う時間';
  }
}

どちらの方法を使用しても、ゲッターはプロパティのように直感的にアクセスできます。

全体のコードと実行結果

void main() {
  final obj = Obj();
  print(obj.timeCheck);
  print(obj.timeChecker);
}

class Obj {
  final now = DateTime.now();
  final time = DateTime.now();
  
  String get timeCheck => now == time ? '同じ時間' : '違う時間';
  
  String get timeChecker {
    if(now == time) {
      return '同じ時間';
    } else {
      return '違う時間';
    }
  }
}

Flutterで使用した例

正規表現を使用して、ヴァリデーションを持たせた機能を作ってみました。

  • パスワードが6桁以上で、小文字、大文字、数字を含んでいる
  • メールアドレスは、@を含んでいて、大文字、小文字で8文字以上にする
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: FormPage(),
    );
  }
}

class FormPage extends StatefulWidget {
  @override
  _FormPageState createState() => _FormPageState();
}

class _FormPageState extends State<FormPage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();

  bool get isPasswordValid {
    final RegExp passwordRegex = RegExp(r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{6,}$');
    return passwordRegex.hasMatch(_passwordController.text);
  }

  bool get isEmailValid {
    final RegExp emailRegex = RegExp(r'^[A-Za-z0-9]+@[A-Za-z0-9]+\.[A-Za-z0-9]+$');
    return emailRegex.hasMatch(_emailController.text);
  }

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      // フォームが正常にバリデーションされた場合の処理
      // ここでフォームデータを送信したり、保存したりできます
      print('Password: ${_passwordController.text}');
      print('Email: ${_emailController.text}');
    }
  }

  @override
  void dispose() {
    _passwordController.dispose();
    _emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Form Validation')),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: [
              TextFormField(
                controller: _passwordController,
                decoration: InputDecoration(labelText: 'Password'),
                validator: (value) {
                  if (!isPasswordValid) {
                    // エラー時にスナックバーを表示
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Invalid password')),
                    );
                    return '';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                validator: (value) {
                  if (!isEmailValid) {
                    // エラー時にスナックバーを表示
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Invalid email')),
                    );
                    return '';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

最後に

ゲッターは、あまり使ったことないので、なぜ使うのか考えていました。引数がいらない関数であり、ロジックによっては、1行でかけるので、便利な機能であることは今回理解できました。

1
0
1

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
1
0