你可以试着用这种方式实现它
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MyHomePage(title: 'DropDown'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String? dropdownValue;
List<Product> products = [
Product(name: 'Europe', type: 'sep'),
Product(name: 'Championship league', type: 'data'),
Product(name: 'Europa league', type: 'data'),
Product(name: 'England', type: 'sep'),
Product(name: 'Premier league', type: 'data'),
Product(name: 'league one', type: 'data'),
Product(name: 'league Two', type: 'data'),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SizedBox(
width: 500.0,
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
hint: const Text('Championship'),
value: dropdownValue,
items: products.map((value) {
return DropdownMenuItem(
enabled: value.type == 'sep' ? false : true,
value: value.name,
child: value.type == 'data'
? Text(value.name)
: DropdownMenuItemSeparator(name: value.name));
}).toList(),
onChanged: (newValue) {
setState(() {
dropdownValue = newValue!;
});
},
),
),
),
),
);
}
}
class Product {
final String name;
final String type;
Product({required this.name, required this.type});
}
class DropdownMenuItemSeparator<T> extends DropdownMenuItem<T> {
final String name;
DropdownMenuItemSeparator({required this.name, Key? key})
: super(
key: key,
child: Text(
name,
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.bold, color: Colors.black),
), // Trick the assertion.
);
}