Flutter中如何用布尔值控制文本样式?
当然可以,以下几种常见方式实现用布尔值控制容器内所有文本样式
1. 直接在Text组件内通过三元运算符设置
适合容器内文本数量较少的场景,直接在每个Text的style属性里根据布尔值切换样式:
bool isDarkMode = false; Container( color: isDarkMode ? Colors.grey[900] : Colors.white, padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "主标题", style: TextStyle( color: isDarkMode ? Colors.white : Colors.black, fontSize: isDarkMode ? 22 : 20, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 8), Text( "副标题内容", style: TextStyle( color: isDarkMode ? Colors.grey[300] : Colors.grey[700], fontSize: 16, ), ), ], ), )
2. 提取样式变量复用逻辑
当容器内文本较多、样式有重复时,把根据布尔值生成的TextStyle抽成变量,减少重复代码:
bool isDarkMode = false; // 提取标题样式 TextStyle get _titleStyle => TextStyle( color: isDarkMode ? Colors.white : Colors.black, fontSize: isDarkMode ? 22 : 20, fontWeight: FontWeight.bold, ); // 提取内容样式 TextStyle get _contentStyle => TextStyle( color: isDarkMode ? Colors.grey[300] : Colors.grey[700], fontSize: 16, ); Container( color: isDarkMode ? Colors.grey[900] : Colors.white, padding: const EdgeInsets.all(16), child: Column( children: [ Text("主标题", style: _titleStyle), Text("内容1", style: _contentStyle), Text("内容2", style: _contentStyle), ], ), )
3. 使用局部Theme统一控制
如果容器内有大量文本,且需要统一管理样式规则,用Theme组件在容器范围内覆盖主题,容器内的Text会自动继承主题样式:
bool isDarkMode = false; Container( color: isDarkMode ? Colors.grey[900] : Colors.white, padding: const EdgeInsets.all(16), child: Theme( data: isDarkMode ? ThemeData.dark().copyWith( textTheme: const TextTheme( titleLarge: TextStyle(fontSize: 22, fontWeight: FontWeight.bold), bodyMedium: TextStyle(fontSize: 16), ), ) : ThemeData.light().copyWith( textTheme: const TextTheme( titleLarge: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), bodyMedium: TextStyle(fontSize: 16, color: Colors.grey[700]), ), ), child: Column( children: [ Text("主标题", style: Theme.of(context).textTheme.titleLarge), Text("内容文本", style: Theme.of(context).textTheme.bodyMedium), Text("更多内容", style: Theme.of(context).textTheme.bodyMedium), ], ), ), )
内容的提问来源于stack exchange,提问作者Joshua Shen
相关产品推荐
相关产品推荐

