media_query.dart 2.51 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';

7
class AdaptedListItem extends StatelessWidget {
8
  const AdaptedListItem({ super.key, required this.name });
9 10 11

  final String name;

12
  @override
13
  Widget build(BuildContext context) {
14
    return Row(
15
      children: <Widget>[
16
        Container(
17 18
          width: 32.0,
          height: 32.0,
19
          margin: const EdgeInsets.all(8.0),
20
          color: Colors.lightBlueAccent.shade100,
21
        ),
22 23
        Text(name),
      ],
24 25 26 27
    );
  }
}

28
class AdaptedGridItem extends StatelessWidget {
29
  const AdaptedGridItem({ super.key, required this.name });
30 31 32

  final String name;

33
  @override
34
  Widget build(BuildContext context) {
35 36
    return Card(
      child: Column(
37
        children: <Widget>[
38 39
          Expanded(
            child: Container(
40
              color: Colors.lightBlueAccent.shade100,
41
            ),
42
          ),
43
          Container(
44
            margin: const EdgeInsets.only(left: 8.0),
45
            child: Row(
46
              children: <Widget>[
47
                Expanded(
48
                  child: Text(name),
49
                ),
50
                const IconButton(
51
                  icon: Icon(Icons.more_vert),
52 53 54 55 56 57 58
                  onPressed: null,
                ),
              ],
            ),
          ),
        ],
      ),
59 60 61 62 63 64 65 66
    );
  }
}

const double _kListItemExtent = 50.0;
const double _kMaxTileWidth = 150.0;
const double _kGridViewBreakpoint = 450.0;

67
class AdaptiveContainer extends StatelessWidget {
68
  const AdaptiveContainer({ super.key, required this.names });
69 70 71

  final List<String> names;

72
  @override
73
  Widget build(BuildContext context) {
74
    if (MediaQuery.of(context).size.width < _kGridViewBreakpoint) {
75
      return ListView(
76
        itemExtent: _kListItemExtent,
77
        children: names.map<Widget>((String name) => AdaptedListItem(name: name)).toList(),
78 79
      );
    } else {
80
      return GridView.extent(
81
        maxCrossAxisExtent: _kMaxTileWidth,
82
        children: names.map<Widget>((String name) => AdaptedGridItem(name: name)).toList(),
83 84 85 86 87
      );
    }
  }
}

88
List<String> _initNames() => List<String>.generate(30, (int i) => 'Item $i');
89 90 91 92

final List<String> _kNames = _initNames();

void main() {
93
  runApp(MaterialApp(
94
    title: 'Media Query Example',
95 96
    home: Scaffold(
      appBar: AppBar(
97
        title: const Text('Media Query Example'),
98
      ),
99 100
      body: Material(child: AdaptiveContainer(names: _kNames)),
    ),
101 102
  ));
}