flexでスペースを分け合う
CoddyのFlutterジャーニー「画面サイズに合わせたレイアウト」セクションの一部。レッスン 2/30。
Rowの2つの子要素がどちらもExpandedの場合、スペースを均等に分け合います。390ピクセルのスマートフォンでは、それぞれ195ピクセルです。
不均等に分けるには、Expandedにflex:を指定します。これはサイズではなく、分け前です。Flutterは分け前を合計し、その比率でスペースを分割します。
Row(
children: [
Expanded(flex: 3, child: Container(color: Colors.red)),
Expanded(flex: 1, child: Container(color: Colors.blue)),
],
)分け前の合計は4なので、赤は行の4分の3、青は4分の1を占めます。flex:のない子要素の分け前は1です。
分け前は全体に対する割合なので、どの画面幅でもレイアウトの比率は保たれます。
チャレンジ
簡単Chart ボックスの幅を Notes ボックスの幅の2倍にしてください。スマートフォンでは、それぞれ260ピクセルと130ピクセルです。
自分で試してみよう
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('Dashboard')),
body: Column(
children: [
Row(
children: [
Expanded(
child: Container(
height: 120,
color: Colors.teal,
child: const Center(
child: Text('Chart', style: TextStyle(color: Colors.white)),
),
),
),
Expanded(
child: Container(
height: 120,
color: Colors.amber,
child: const Center(child: Text('Notes')),
),
),
],
),
],
),
),
);
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
画面サイズに合わせたレイアウトのすべてのレッスン
自分で練習してみよう: Flutterオンラインコンパイラ