Skip to content

Instantly share code, notes, and snippets.

@mono0926
Last active February 20, 2023 03:04
Show Gist options
  • Save mono0926/eb4354d7d0b43780340eaeff960f8020 to your computer and use it in GitHub Desktop.
Save mono0926/eb4354d7d0b43780340eaeff960f8020 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(const App());
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
// 説明しやすくするため、幅を200固定で確保
child: Container(
color: Colors.grey[300],
width: 200,
child: Column(
children: [
const Text('灰色の幅は200'),
const Divider(),
const Text('中身が膨らむものは同じ結果に'),
const SizedBox(height: 8),
const Text('SizedBox'),
Expanded(
child: SizedBox(
// Overflowエラーにならず、与えられた幅200に普通に収まる
width: 300,
// Containerは可能な限り膨らむ
child: Container(
color: Colors.red,
child: const Text(
'''
SizedBox(width: 300)
Overflowエラーにならない👌''',
),
),
),
),
Expanded(
child: SizedBox(
width: 100,
child: Container(
color: Colors.green,
child: const Text('SizedBox(width: 100)'),
),
),
),
const Text('ConstrainedBox'),
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 300),
child: Container(
color: Colors.redAccent,
child: const Text('BoxConstraints(maxWidth: 300)'),
),
),
),
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 100),
child: Container(
color: Colors.greenAccent,
child: const Text('BoxConstraints(maxWidth: 100)'),
),
),
),
const Divider(),
const Text('中身のサイズに従う場合は違う結果に'),
const SizedBox(height: 8),
const Text('SizedBox(width:100)'),
const Expanded(
child: SizedBox(
// childの幅に関わらず、100の幅になる
width: 100,
child: ColoredBox(
color: Colors.yellow,
child: Text('foo'),
),
),
),
const Text('BoxConstraints(maxWidth: 100)'),
Expanded(
child: ConstrainedBox(
// childの幅が100未満ならその最小限の幅に
constraints: const BoxConstraints(maxWidth: 100),
child: const ColoredBox(
color: Colors.yellowAccent,
child: Text('foo'),
),
),
),
Expanded(
child: ConstrainedBox(
// childの幅が100以上なら100に
constraints: const BoxConstraints(maxWidth: 100),
child: ColoredBox(
color: Colors.yellow,
child: Text('foo' * 10),
),
),
),
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment