Flutter中如何在选中下拉选项后显示对应描述文本?
解决方案
你的代码核心问题是缺少展示动物描述文本和图片的UI组件,选中下拉选项后没有对应的控件来呈现内容。以下是修改后的完整代码,实现了下拉选择动物、展示对应图片和描述文本的需求:
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Demo', theme: ThemeData(primarySwatch: Colors.blue), home: const MyHomePage(title: 'Section 2'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { String _selectedAnimal = "Dog"; // 存储动物名称对应的图片和描述 final Map<String, Map<String, String>> animalDetails = { "Dog": { "image": "https://images.unsplash.com/photo-1507146426996-ef05306b995a?ixlib=rb-4.0.3&auto=format&fit=crop&w=1350&q=80", "description": "A dog is a domestic mammal of the family Canidae and the order Carnivora." }, "Cat": { "image": "https://images.unsplash.com/photo-1514888286974-6c03e2ca1dba?ixlib=rb-4.0.3&auto=format&fit=crop&w=1350&q=80", "description": "Cats have a strong flexible body, quick reflexes, sharp teeth." }, "Lion": { "image": "https://images.unsplash.com/photo-1564349683136-77e08dba1ef7?ixlib=rb-4.0.3&auto=format&fit=crop&w=1350&q=80", "description": "Lions are large cats of the genus Panthera native to Africa and India." } }; late List<String> _animals; @override void initState() { super.initState(); // 直接从animalDetails中提取动物名称列表 _animals = animalDetails.keys.toList(); } @override Widget build(BuildContext context) { // 根据选中的动物获取对应的图片和描述 final currentAnimalData = animalDetails[_selectedAnimal]!; return Scaffold( appBar: AppBar(title: Text(widget.title)), body: Container( margin: const EdgeInsets.all(15), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ const SizedBox(height: 23), const Text( "Animal", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18), ), Container( width: 400, child: DropdownButton<String>( value: _selectedAnimal, isExpanded: true, // 让下拉框占满容器宽度 onChanged: (newValue) { setState(() { _selectedAnimal = newValue!; }); }, items: _animals.map((animal) { return DropdownMenuItem( value: animal, child: Text(animal), ); }).toList(), ), ), const SizedBox(height: 23), // 展示动物图片 Center( child: Image.network( currentAnimalData["image"]!, height: 200, fit: BoxFit.cover, ), ), const SizedBox(height: 16), // 展示动物描述文本 Text( currentAnimalData["description"]!, style: const TextStyle(fontSize: 16), ), ], ), ), ); } }
关键修改说明:
- 新增
animalDetails映射,统一管理每个动物的图片地址和描述文本,便于动态获取内容 - 给
DropdownButton指定泛型<String>提升类型安全性,设置isExpanded: true让下拉框适配容器宽度 - 在
build方法中根据_selectedAnimal获取当前选中动物的对应数据,动态渲染图片和文本 - 简化动物列表初始化逻辑,直接从
animalDetails的键集合中提取,去掉冗余方法 - 添加
Center组件包裹图片,设置固定高度和适配模式,优化展示效果
内容的提问来源于stack exchange,提问作者Shweta
相关产品推荐
相关产品推荐

