LoginSignup
3
2

More than 3 years have passed since last update.

Card Widgetの大きさを自分で調整するには

Posted at

記事の目的

Card Widgetを使うときに、中身にCardの大きさを固定できる方法を説明する

方法

Card Widgetは基本的にchildのコンテンツの大きさに依存して大きさが変化する。
Sizedboxで囲むことで、height,widthを自分で設定することができる。
下のコードではカード1はそのまま、カード2はSizedboxで囲み自分でheight,widthを設定した。

Screenshot_1616591407.png

コード例

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: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        //SafeAreaはスマホの一番上部など被りたくないところにコンテンツを表示させないウィジット
        body: SafeArea(
          //Center widgetを使うことでCardを中央よせすることができる。
          child: Center(
            child: Column(
              //columnの縦の列の並び方を決めるのがmainAxisAlignment
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                //ただのCardを使う場合、childの大きさにCardが自動で設定される。
                Card(
                  child: Text('カード1',style: TextStyle(fontSize: 32.0),),color: Colors.red,),
                //SizedBoxでCardの高さ、幅を設定することができる
                SizedBox(
                  child: Card(
                      child: Center(
                          child: Text('カード2',style: TextStyle(fontSize: 32.0),)),color:Colors.blueAccent),
                  height: 100,
                  width: 200,
                )
              ],
            ),
          ),
        ),
      )
    );
  }
}

SizedBoxで囲うのはCard Widgetのみならず汎用性が高いと感じたのでメモしました。
便利ですね!

3
2
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
3
2