Flutter动画搜索栏插件animated_type_ahead_searchbar的使用

Flutter 动画搜索栏插件 animated_type_ahead_searchbar 的使用

这个插件将 animated_searchbarflutter_typeahead 合并在一起,提供了一个带有动画效果的智能搜索栏。

Android Emulator - Pixel_5_API_29_5554 2022-01-08 13-17-39

特性

  • 在其他小部件上方浮动的覆盖层中显示建议。
  • 允许你通过构建器函数指定建议的外观。
  • 允许你指定用户点击建议时会发生什么。
  • 提供高自定义化;你可以自定义建议框的装饰。

安装

请参考 这些说明

使用

final List searchData = const [
  'Steel Pan',
  'Harp',
  'Cake',
  'Maracas',
  'Clarinet',
  'Odyssey',
  'Slide Whistle',
  'Piano',
];

AnimatedTypeAheadSearchBar(
  width: MediaQuery.of(context).size.width * 0.88,
  onSuffixTap: null,
  itemBuilder: (String suggestion) {
    return Material(
      color: Colors.white,
      borderOnForeground: false,
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Flexible(
              child: Text(
                suggestion,
                overflow: TextOverflow.visible,
              ),
            ),
          ],
        ),
      ),
    );
  },
  onSuggestionSelected: (suggestion) {
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => Home(text: suggestion)),
    );
    FocusScope.of(context).unfocus();
  },
  suggestionCallback: (String pattern) {
    List<String> suggestions = [];
    if (pattern.length < 2) return suggestions;
    for (var i = 0; i < searchData.length; i++) {
      if (searchData[i].toLowerCase().contains(pattern.toLowerCase())) {
        suggestions.add(searchData[i]);
      }
    }
    return suggestions;
  },
);

更多关于Flutter动画搜索栏插件animated_type_ahead_searchbar的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter动画搜索栏插件animated_type_ahead_searchbar的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用animated_type_ahead_searchbar插件的示例代码。这个插件允许你创建一个带有动画效果的搜索栏,用户可以在其中输入文本以进行搜索,并且结果会动态显示。

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

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

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

接下来,下面是一个完整的示例代码,展示如何使用animated_type_ahead_searchbar插件:

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

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

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

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<String> suggestions = List<String>.generate(100, (i) => "Item $i");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Animated Type Ahead SearchBar Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: AnimatedTypeAheadSearchBar<String>(
          suggestionsCallback: (String pattern) async {
            // 模拟异步搜索
            await Future.delayed(Duration(milliseconds: 300));
            return suggestions
                .where((suggestion) =>
                    suggestion.toLowerCase().contains(pattern.toLowerCase()))
                .toList();
          },
          itemBuilder: (context, suggestion) {
            return ListTile(
              leading: Icon(Icons.label),
              title: Text(suggestion),
            );
          },
          onSuggestionSelected: (String suggestion) {
            // 当用户选择一个建议时的回调
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text("Selected: $suggestion")),
            );
          },
          textFieldConfiguration: TextFieldConfiguration(
            autofocus: true,
            decoration: InputDecoration(
              prefixIcon: Icon(Icons.search),
              labelText: 'Search...',
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ),
    );
  }
}

代码说明:

  1. 依赖导入

    • 导入flutter/material.dartanimated_type_ahead_searchbar包。
  2. 主应用

    • 使用MaterialApp作为根组件。
    • 设置应用的主题。
  3. 主页面

    • 使用StatefulWidget来管理搜索栏的状态。
    • 定义一个包含100个字符串的suggestions列表,作为搜索建议。
  4. 搜索栏

    • 使用AnimatedTypeAheadSearchBar组件。
    • suggestionsCallback:当用户输入文本时,这个回调会被调用,返回一个匹配搜索模式的建议列表。这里使用了一个模拟的异步搜索,通过Future.delayed来模拟网络延迟。
    • itemBuilder:用于构建每个搜索建议的UI。这里使用ListTile来显示每个建议。
    • onSuggestionSelected:当用户选择一个建议时的回调。这里使用ScaffoldMessenger.of(context).showSnackBar来显示一个Snackbar,告知用户选择了哪个建议。
    • textFieldConfiguration:配置搜索栏的文本字段,包括自动聚焦、装饰等。

这个示例展示了如何使用animated_type_ahead_searchbar插件来创建一个带有动画效果的搜索栏,并处理用户的搜索输入和选择。你可以根据自己的需求进一步自定义和扩展这个示例。

回到顶部