點燈坊

失くすものさえない今が強くなるチャンスよ

DropdownButton 不顯示下方橫線

Sam Xiao's Avatar 2024-10-17

DropdownButton 預設在下方會有一條橫線,也可加以取消顯示。

Version

Dart 3.5

Flutter

underline01

  • Android 與 iOS 都成功使用 DropdownButton 顯示
import 'package:flutter/material.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  
  State<Home> createState() {
    return _Home();
  }
}

class _Home extends State<Home> {
  int? _selectedValue = 1;

  
  Widget build(BuildContext context) {
    var appBar = AppBar(
      title: const Text('DropdownButton'),
    );

    var dropdownMenuItems = const [
      DropdownMenuItem<int>(
        value: 1,
        child: Text('One'),
      ),
      DropdownMenuItem<int>(
        value: 2,
        child: Text('Two'),
      ),
      DropdownMenuItem<int>(
        value: 3,
        child: Text('Three'),
      ),
    ];

    var dropdownButton = DropdownButton<int>(
      value: _selectedValue,
      underline: const SizedBox.shrink(),
      onChanged: (int? newValue) {
        setState(() {
          _selectedValue = newValue;
        });
      },
      items: dropdownMenuItems,
    );

    var selectedValue = Padding(
      padding: const EdgeInsets.only(left: 16.0),
      child: Text('$_selectedValue'),
    );

    var body = Padding(
      padding: const EdgeInsets.only(left: 16.0),
      child: Row(
        children: [dropdownButton, selectedValue],
      ),
    );

    return Scaffold(
      appBar: appBar,
      body: body,
    );
  }
}

Line 38

underline: const SizedBox.shrink(),
  • underline:指定 SizedBox.shrink()

Conclusion

  • DropdownButton 可設定 underline 使 UI 更平面