Flutter标签管理插件flutter_tagging的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter标签管理插件flutter_tagging的使用

简介

flutter_tagging 是一个用于 Flutter 应用程序的标签或多重选择功能的插件。它非常适合添加标签或标签选择表单。

使用示例

示例代码

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_syntax_view/flutter_syntax_view.dart';
import 'package:flutter_tagging/flutter_tagging.dart';

void main() => runApp(MyApp());

///
class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Tagging Demo',
      theme: ThemeData(
        primarySwatch: Colors.green,
        scaffoldBackgroundColor: Colors.white,
      ),
      home: MyHomePage(),
    );
  }
}

///
class MyHomePage extends StatefulWidget {
  [@override](/user/override)
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _selectedValuesJson = 'Nothing to show';
  late final List<Language> _selectedLanguages;

  [@override](/user/override)
  void initState() {
    super.initState();
    _selectedLanguages = [];
  }

  [@override](/user/override)
  void dispose() {
    _selectedLanguages.clear();
    super.dispose();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tagging Demo'),
      ),
      body: Column(
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: FlutterTagging<Language>(
              initialItems: _selectedLanguages,
              textFieldConfiguration: TextFieldConfiguration(
                decoration: InputDecoration(
                  border: InputBorder.none,
                  filled: true,
                  fillColor: Colors.green.withAlpha(30),
                  hintText: 'Search Tags',
                  labelText: 'Select Tags',
                ),
              ),
              findSuggestions: LanguageService.getLanguages,
              additionCallback: (value) {
                return Language(
                  name: value,
                  position: 0,
                );
              },
              onAdded: (language) {
                // 当添加到标签按钮被按下时触发API调用
                return language;
              },
              configureSuggestion: (lang) {
                return SuggestionConfiguration(
                  title: Text(lang.name),
                  subtitle: Text(lang.position.toString()),
                  additionWidget: Chip(
                    avatar: Icon(
                      Icons.add_circle,
                      color: Colors.white,
                    ),
                    label: Text('Add New Tag'),
                    labelStyle: TextStyle(
                      color: Colors.white,
                      fontSize: 14.0,
                      fontWeight: FontWeight.w300,
                    ),
                    backgroundColor: Colors.green,
                  ),
                );
              },
              configureChip: (lang) {
                return ChipConfiguration(
                  label: Text(lang.name),
                  backgroundColor: Colors.green,
                  labelStyle: TextStyle(color: Colors.white),
                  deleteIconColor: Colors.white,
                );
              },
              onChanged: () {
                setState(() {
                  _selectedValuesJson = _selectedLanguages
                      .map<String>((lang) => '\n${lang.toJson()}')
                      .toList()
                      .toString();
                  _selectedValuesJson =
                      _selectedValuesJson.replaceFirst('}]', '}\n]');
                });
              },
            ),
          ),
          SizedBox(
            height: 20.0,
          ),
          Expanded(
            child: SyntaxView(
              code: _selectedValuesJson,
              syntax: Syntax.JAVASCRIPT,
              withLinesCount: false,
              syntaxTheme: SyntaxTheme.standard(),
            ),
          ),
        ],
      ),
    );
  }
}

/// LanguageService
class LanguageService {
  /// 模拟从网络API获取语言数据,并延迟500毫秒。
  static Future<List<Language>> getLanguages(String query) async {
    await Future.delayed(Duration(milliseconds: 500), null);
    return <Language>[
      Language(name: 'JavaScript', position: 1),
      Language(name: 'Python', position: 2),
      Language(name: 'Java', position: 3),
      Language(name: 'PHP', position: 4),
      Language(name: 'C#', position: 5),
      Language(name: 'C++', position: 6),
    ]
        .where((lang) => lang.name.toLowerCase().contains(query.toLowerCase()))
        .toList();
  }
}

/// Language Class
class Language extends Taggable {
  ///
  final String name;

  ///
  final int position;

  /// 创建语言对象
  Language({
    required this.name,
    required this.position,
  });

  [@override](/user/override)
  List<Object> get props => [name];

  /// 将类转换为JSON字符串。
  String toJson() => '''
  {
    "name": $name,
    "position": $position
  }''';
}

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

1 回复

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


当然,以下是如何在Flutter项目中使用flutter_tagging插件来实现标签管理功能的一个简单示例。这个插件允许用户输入和管理多个标签。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加flutter_tagging依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_tagging: ^2.0.0  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 导入包

在你的Dart文件中导入flutter_tagging包:

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

3. 使用TagInput组件

下面是一个完整的示例,展示如何在Flutter应用中使用flutter_tagging插件:

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Tagging Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TaggingExample(),
    );
  }
}

class TaggingExample extends StatefulWidget {
  @override
  _TaggingExampleState createState() => _TaggingExampleState();
}

class _TaggingExampleState extends State<TaggingExample> {
  final TextEditingController _controller = TextEditingController();
  List<String> _tags = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Tagging Example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Selected Tags:',
              style: TextStyle(fontSize: 18),
            ),
            SizedBox(height: 10),
            Wrap(
              spacing: 6,
              runSpacing: 6,
              children: List.generate(
                _tags.length,
                (index) => Chip(
                  label: Text(_tags[index]),
                  backgroundColor: Colors.blue.shade200,
                  onDelete: () {
                    setState(() {
                      _tags.removeAt(index);
                    });
                  },
                ),
              ),
            ),
            SizedBox(height: 20),
            TagInput(
              textController: _controller,
              suggestions: ['Flutter', 'Dart', 'React', 'Angular', 'Vue'],
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Add a tag',
                hintText: 'Press enter to add',
              ),
              onChanged: (tags) {
                setState(() {
                  _tags = tags;
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}

解释

  1. 依赖管理:在pubspec.yaml中添加flutter_tagging依赖。
  2. 导入包:在需要使用标签管理的Dart文件中导入flutter_tagging包。
  3. 使用TagInput组件
    • TagInput组件允许用户输入标签,并且可以从预设的建议列表中选择。
    • textController:用于控制标签输入的文本控制器。
    • suggestions:标签建议列表。
    • decoration:输入框的装饰。
    • onChanged:当标签列表发生变化时的回调。
  4. 显示已选择的标签:使用WrapChip组件来显示已选择的标签,并提供删除功能。

这个示例展示了如何使用flutter_tagging插件来创建和管理标签,包括添加、显示和删除标签。你可以根据需求进一步自定义和扩展这个示例。

回到顶部