🦍

【flutter】componentの作り方

2022/06/14に公開

flutterはクラスベースでUIを構築していくため、Reactエンジニアが始めるとなかなか慣れるのに時間がかかるかもしれません。

初めに

こんな感じのUIがあるとします。
画面には[This is a Flutter]と表示があります。

class _MainPage extends State<MainPage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('study_dart'),
        ),
        body: Center(
            child: Column(children: const <Widget>[
          Text('This is a Flutter'),
        ])));
  }
}

Textをコンポーネント化

このTextのをコンポーネント化してみようと思います。

まずは、コンポーネントを作成
クラス名はCompTitleとします。

class CompTitle extends StatelessWidget {
  final String title;
  CompTitle({required this.title});

  
  Widget build(BuildContext context) {
    return Text(title);
  }
}

そしてこのコンポーネントをUIに組み込みます

class _MainPage extends State<MainPage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('study_dart'),
        ),
        body: Center(
            child: Column(children: <Widget>[
          CompTitle(
            title: 'This is a flutter',
          ),
        ])));
  }
}

これで同じように表示されたと思います。

Buttonをコンポーネント化

Textをコンポーネント化して使いまわすイメージがあまりわかないと思うので、Buttonをコンポーネント化し引数を2つ渡してみようと思います。

まずはButtonのコンポーネントを作成。
引数はlabel onPressedです。

class CompButton extends StatelessWidget {
  final String label;
  final GestureTapCallback onPressed;

  CompButton({required this.label, required this.onPressed});

  
  Widget build(BuildContext context) {
    return OutlinedButton(
      onPressed: onPressed,
      child: Text(label),
    );
  }
}

そしてUIに組み込む

class _MainPage extends State<MainPage> {
  
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('study_dart'),
        ),
        body: Center(
            child: Column(children: <Widget>[
          CompTitle(
            title: 'This is a flutter',
          ),
          CompButton(
            label: 'Button',
            onPressed: () {
              print('Button pressed');
            },
          )
        ])));
  }
}

これで、ボタンの中身とクリック時のイベントを引数に持つコンポーネントの完成!

webフロントエンドのようにnativeもコンポーネントで作るのが主流のようです。

Discussion

ログインするとコメントできます