乐闻世界logo
搜索文章和话题

How to show Icon in Text widget in flutter?

1个答案

1

In Flutter, to display icons within the Text widget, we typically use the RichText widget in combination with TextSpan and WidgetSpan. This is because the Text widget itself does not natively support embedding icons directly. Here is a specific example demonstrating how to achieve this:

dart
import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Flutter Demo'), ), body: Center( child: RichText( text: TextSpan( style: TextStyle( color: Colors.black, fontSize: 20, ), children: <TextSpan>[ TextSpan(text: '这是一个图标 '), WidgetSpan( child: Icon(Icons.star, size: 24, color: Colors.red), ), TextSpan(text: ' 在文本中'), ], ), ), ), ), ); } }

In this example:

  1. We create a RichText widget.
  2. We use TextSpan to include plain text.
  3. We use WidgetSpan to embed the Icon widget.
  4. Icon(Icons.star, size: 24, color: Colors.red) is the displayed icon, which you can customize the icon, size, and color.

This layout approach allows us to flexibly embed icons within text while maintaining other text properties such as font size and color consistency. This is particularly useful when creating rich user interfaces, such as embedding icons in tooltips, buttons, or list items to enhance user experience.

2024年8月8日 01:25 回复

你的答案