Menu
CoddyTech

ウィジェットを上に重ねる

CoddyのFlutterジャーニー「画面サイズに合わせたレイアウト」セクションの一部。レッスン 10/30。

Columnは子要素を縦に並べ、Rowは横に並べます。Stackは、机の上に紙を重ねるように、子要素を重ねます。

Stack(
  children: [
    Container(height: 200, color: Colors.grey),
    const Text('On top'),
  ],
)

最初の子要素は最初に描画され、一番下に配置されます。その後の各子要素は、それより前の子要素の上に描画されます。つまり、写真が最初に配置され、その上に載るラベルが最後に配置されます。

子要素はStackの左上隅から配置され、Stackの大きさは最も大きな子要素に合わせられます。バッジやラベル、再生ボタンを画像の上に配置するのはこのためです。

challenge icon

チャレンジ

簡単

SALEバッジは写真の下にあります。写真の上に重ねるには、2つを含むColumnをStackに変更し、バッジが手前に表示されるようにします。

自分で試してみよう

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Shop')),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              Column(
                children: [
                  Container(
                    height: 200,
                    color: Colors.blueGrey.shade100,
                    child: const Center(child: Icon(Icons.image, size: 64)),
                  ),
                  Container(
                    padding: const EdgeInsets.all(8),
                    color: Colors.red,
                    child: const Text('SALE', style: TextStyle(color: Colors.white)),
                  ),
                ],
              ),
              const SizedBox(height: 12),
              const Text('Running shoes', style: TextStyle(fontSize: 20)),
            ],
          ),
        ),
      ),
    );
  }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

画面サイズに合わせたレイアウトのすべてのレッスン

自分で練習してみよう: Flutterオンラインコンパイラ