LoginSignup
6
4

More than 3 years have passed since last update.

Flutterの名前付きコールバック ValueChanged

Last updated at Posted at 2021-03-23

動機

しばらく書かないと、すぐ忘れてしまうので。

以前、以下のVoidCallbackの記事を書いたところ、忘れづらくなった感覚があったり、

Web上にあると、どこからでも参照出来るので便利であると感じています。

使用例

Flutter 2.0.1 で動作確認しました。


import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ValueChanged Sample',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

/// ページ
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'ValueChanged',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
      ),
      // body: _List(),
      body: _Body(),
    );
  }
}

/// body
class _Body extends StatefulWidget {
  @override
  __BodyState createState() => __BodyState();
}

class __BodyState extends State<_Body> {
  /// フードリスト
  final foods = [
    '寿司',
    'ラーメン',
    'カレー',
    '焼肉',
    'ハンバーグ',
  ];

  var selectedFood = '食べ物を選択して下さい';

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            itemCount: foods.length,
            itemBuilder: (
              BuildContext context,
              int index,
            ) =>
                FoodListItem(
              title: foods[index],
              onTap: (title) => setState(
                () => selectedFood = title,
              ),
            ),
          ),
        ),
        SizedBox(height: 30),
        Text(selectedFood),
        SizedBox(height: 80),
      ],
    );
  }
}

// 食べ物のリストアイテム
class FoodListItem extends StatelessWidget {
  const FoodListItem({
    this.title,
    this.onTap,
  });

  final String title;
  final ValueChanged onTap;

  @override
  Widget build(BuildContext context) {
    return Card(
      child: InkWell(
        // タップされた食べ物の名前を返す
        onTap: () => onTap(title),
        child: Container(
          height: 65,
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.only(left: 15),
          child: Text(
            title,
          ),
        ),
      ),
    );
  }
}

タップした食べ物が、画面下部のラベルに表示されます。

スクリーンショット 2021-03-24 0.52.09.png

メモ

定義を確認すると、同じ意味になるのですが、

final ValueChanged<String> onTap;

の部分を、以下のように書いてあることも多いです。むしろValueChangedは、ほとんど見ないくらいな気もします。(これでよく混乱しています。)

final void Function(String) onTap;
6
4
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
6
4