develop/Flutter

[Flutter] dropdown button 만들기 iOS 스타일과 안드로이드 스타일

방뎁 2023. 4. 17. 08:58
반응형

Cupertino와 Material

우선 Cupertino는 iOS 스타일이고, Material은 android 스타일이다. 

Material app 으로 감싸고 있든, cupertino 로 감싸고 있든 dropdown은 어떤 스타일이든 만들 수 있다. 

 

dropdown button 만들기 

 

iOS스타일

우선 iOS 스타일로 dropdown 을 만들때에는 아래의 공식 사이트를 참고 했다. 

https://docs.flutter.dev/development/ui/widgets/cupertino

 

Cupertino (iOS-style) widgets

A catalog of Flutter's widgets implementing the Cupertino design language.

docs.flutter.dev

 

// dropdown button에 사용될 목록들
final List<String> _themeMode = <String>[
    'system',
    'dark',
    'light',
  ]; 

  int _selectedMode = 0; // 선택된 인덱스

// -- 팝업 --
  void _showDialog(Widget child) {
    showCupertinoModalPopup<void>(
      context: context,
      builder: (BuildContext context) => Container(
        height: 216,
        padding: const EdgeInsets.only(top: 6.0),
        margin: EdgeInsets.only(
          bottom: MediaQuery.of(context).viewInsets.bottom,
        ),
        color: CupertinoColors.systemBackground.resolveFrom(context),
        child: SafeArea(
          top: false,
          child: child,
        ),
      ),
    );
  }

 

위와 같이 작성 한 뒤, 

import 'package:flutter/cupertino.dart';

CupertinoButton(
    padding: EdgeInsets.zero,
    // Display a CupertinoPicker with list of fruits.
    onPressed: () => _showDialog(
      CupertinoPicker(
        magnification: 1.22,
        squeeze: 1.2,
        useMagnifier: true,
        itemExtent: _kItemExtent,
        // This is called when selected item is changed.
        onSelectedItemChanged: (int selectedItem) {
          setState(() {
            _selectedMode = selectedItem;
          });
        },
        children:
            List<Widget>.generate(_themeMode.length, (int index) {
          return Center(
            child: Text(
              _themeMode[index],
            ),
          );
        }),
      ),
    ),
    child: Text(
      _themeMode[_selectedMode],
      style: const TextStyle(
        fontSize: 22.0,
      ),
    ),
  ),

이렇게 사용하면 된다. 

반응형

import를 잊지 말자!


Android 스타일

안드로이드는 좀 더 간단하다. 

dialog구현부가 없기 때문이다. 

  final List<String> _themeMode = <String>[
    'system',
    'dark',
    'light',
  ];
  String selectedTheme = 'system';

 

위와 같이 작성한 뒤, 

 

DropdownButton(
    value: selectedTheme,
    items: _themeMode.map((String item) {
      return DropdownMenuItem<String>(
        child: Text('$item'),
        value: item,
      );
    }).toList(),
    onChanged: (dynamic value) {
      setState(() {
        selectedTheme = value;
      });
    },
  ),

이렇게 구현하면 끝!

반응형