Flutter文本标签处理插件tagged_text的使用

Flutter文本标签处理插件tagged_text的使用

TaggedText 库允许轻松构建带标签的文本作为 RichText

通过带标签的文本构建 RichText

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  tagged_text: ... // 最新版本号

使用

查看 /example 文件夹中的示例。

示例代码

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:tagged_text/tagged_text.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Tagged Text Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            //
            // 这是 [TaggedText] 的开始部分。
            //
            TaggedText(
              textAlign: TextAlign.center,
              // 带标签的字符串。
              text: '你已经按了这些按钮之一\n次数为: <v>$_counter</v>\n标签也可以互相跨越',
              // 根 TextSpan 的设置。
              rootSettings: TagSettings(style: textTheme.bodyText1),
              // 每个标签的设置。
              tagsSettings: <String, TagSettings>{
                // 标签 'b' 带有蓝色 accent 颜色,并且点击时触发动作。
                'b': TagSettings(
                  style: textTheme.bodyText2?.apply(color: Colors.blueAccent),
                  recognizer: TapGestureRecognizer()
                    ..onTap = () {
                      _incrementCounter();
                    },
                ),
                // 标签 'v' 带有特定主题。
                'v': TagSettings(style: textTheme.headline6),
                // 标签 'hl' 和 'hr' 相互交叉并合并其设置。
                'hl': TagSettings(
                  style: const TextStyle(
                    backgroundColor: Colors.deepPurple,
                    color: Colors.yellow,
                  ),
                ),
                'hr': TagSettings(
                  style: const TextStyle(
                    color: Colors.deepOrangeAccent,
                  ),
                ),
              },
            ),
            //
            // 这是 [TaggedText] 的结束部分。
            //
            const SizedBox(height: 30),
            // 如果你想仅使用 [TaggedText] 来应用不同的 [TextStyle]
            // 可以自由地使用它。
            TaggedText.style(
              text: '文本 <a>带有 <b>仅</b> 文本</a> 样式',
              rootStyle: textTheme.caption,
              tagsStyles: const <String, TextStyle>{
                'a': TextStyle(
                  backgroundColor: Colors.blueAccent,
                  color: Colors.yellow,
                ),
                'b': TextStyle(
                  color: Colors.deepOrangeAccent,
                ),
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: '增加',
        child: const Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter文本标签处理插件tagged_text的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文本标签处理插件tagged_text的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 tagged_text 插件来处理 Flutter 中文本标签的示例代码。tagged_text 插件允许你在文本中嵌入自定义的标签,并根据这些标签应用不同的样式或逻辑。

首先,确保你的 pubspec.yaml 文件中已经添加了 tagged_text 依赖:

dependencies:
  flutter:
    sdk: flutter
  tagged_text: ^x.y.z  # 请替换为最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来,我们编写一个示例应用,展示如何使用 tagged_text 插件。

import 'package:flutter/material.dart';
import 'package:tagged_text/tagged_text.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Tagged Text Example'),
        ),
        body: Center(
          child: TaggedTextExample(),
        ),
      ),
    );
  }
}

class TaggedTextExample extends StatelessWidget {
  final String taggedText = "Hello [bold]world[/bold]! Welcome to [italic]Flutter[/italic] development.";

  @override
  Widget build(BuildContext context) {
    return TaggedText(
      text: taggedText,
      tags: {
        'bold': (context, child) => Text(
          child.toString(),
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        'italic': (context, child) => Text(
          child.toString(),
          style: TextStyle(fontStyle: FontStyle.italic),
        ),
      },
      textStyle: TextStyle(fontSize: 20),
    );
  }
}

在这个示例中:

  1. taggedText 字符串包含了自定义的标签,如 [bold][italic]
  2. TaggedText 组件用于解析和处理这些标签。
  3. tags 参数是一个映射,定义了每个标签对应的样式或组件。例如,'bold' 标签对应的组件是 Text,并且其样式被设置为粗体。同样,'italic' 标签对应的组件也是 Text,但其样式被设置为斜体。
  4. textStyle 参数定义了默认文本样式。

运行这个应用后,你会看到文本 “Hello world! Welcome to Flutter development.”,其中 “world” 是粗体的,而 “Flutter” 是斜体的。

这个示例展示了如何使用 tagged_text 插件在 Flutter 应用中处理文本标签。你可以根据需要扩展和自定义标签的处理逻辑。

回到顶部