Flutter股票或行情搜索插件ticker_search的使用

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

Flutter股票或行情搜索插件ticker_search的使用

特性

  • 易用的股票代码搜索小部件。
  • 可自定义的股票代码建议,并带有图标。
  • 支持浅色和深色主题。
  • Material 3设计。
  • 返回一个包含所选股票代码对象的StockTicker

准备工作

在开始之前,请确保您的开发机器上已安装Flutter。如果还没有,请访问Flutter官方网站以获取安装指南。

安装

在您的pubspec.yaml文件中添加以下依赖项:

dependencies:
  ticker_search: ^0.0.1
  stock_market_data: ^0.0.9

运行flutter pub get以安装这些依赖项。

使用方法

首先,导入ticker_search包:

import 'package:ticker_search/ticker_search.dart';

接下来,使用TickerSearch小部件:

final List<StockTicker>? tickers = await showSearch(
  context: context,
  delegate: TickerSearch(
    searchFieldLabel: '添加',
    suggestions: [
      TickerSuggestion(const Icon(Icons.view_headline), '主要', TickersList.main),
      TickerSuggestion(const Icon(Icons.business_sharp), '公司', TickersList.companies),
      TickerSuggestion(const Icon(Icons.precision_manufacturing_outlined), '行业', TickersList.sectors),
      TickerSuggestion(const Icon(Icons.workspaces_outline), '期货', TickersList.futures),
      TickerSuggestion(const Icon(Icons.computer), '加密货币', TickersList.cryptoCurrencies),
      TickerSuggestion(const Icon(Icons.language), '国家', TickersList.countries),
      TickerSuggestion(const Icon(Icons.account_balance_outlined), '债券', TickersList.bonds),
      TickerSuggestion(const Icon(Icons.architecture_sharp), '规模', TickersList.sizes),
    ],
  ),
);

示例代码

以下是一个完整的示例代码,展示了如何使用ticker_search插件:

import 'package:flutter/material.dart';
import 'package:stock_market_data/stock_market_data.dart';
import 'package:ticker_search/ticker_search.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({
    super.key,
  });

  [@override](/user/override)
  Widget build(BuildContext context) => MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData.dark(),
        home: const MyHomePage(title: '股票代码搜索演示'),
      );
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child: SearchWidget(),
            ),
          ],
        ),
      );
}

class SearchWidget extends StatefulWidget {
  const SearchWidget({
    super.key,
  });

  [@override](/user/override)
  State<SearchWidget> createState() => _SearchWidgetState();
}

class _SearchWidgetState extends State<SearchWidget> {
  StockTicker selected = const StockTicker(symbol: '');

  [@override](/user/override)
  Widget build(BuildContext context) {
    final String ticketDescription = TickerResolve.getTickerDescription(selected);

    return Column(
      children: [
        Text('选择: ${selected.symbol} > $ticketDescription'),
        InkWell(
          child: Container(
            color: Colors.lightBlue.withOpacity(0),
            padding: const EdgeInsets.only(
              left: 40,
              right: 40,
              bottom: 30,
            ),
            child: const Icon(
              Icons.add,
            ),
          ),
          onTap: () async {
            final List<StockTicker>? tickers = await showSearch(
              context: context,
              delegate: TickerSearch(
                searchFieldLabel: '搜索股票代码',
                suggestions: [
                  TickerSuggestion(
                    const Icon(Icons.view_headline),
                    '主要',
                    TickersList.main,
                  ),
                  TickerSuggestion(
                    const Icon(Icons.business_sharp),
                    '公司',
                    TickersList.companies,
                  ),
                  TickerSuggestion(
                    const Icon(Icons.precision_manufacturing_outlined),
                    '行业',
                    TickersList.sectors,
                  ),
                  TickerSuggestion(
                    const Icon(Icons.workspaces_outline),
                    '期货',
                    TickersList.futures,
                  ),
                  TickerSuggestion(
                    const Icon(Icons.computer),
                    '加密货币',
                    TickersList.cryptoCurrencies,
                  ),
                  TickerSuggestion(
                    const Icon(Icons.language),
                    '国家',
                    TickersList.countries,
                  ),
                  TickerSuggestion(
                    const Icon(Icons.account_balance_outlined),
                    '债券',
                    TickersList.bonds,
                  ),
                  TickerSuggestion(
                    const Icon(Icons.architecture_sharp),
                    '规模',
                    TickersList.sizes,
                  ),
                ],
              ),
            );

            if (tickers != null && tickers.isNotEmpty) {
              setState(() {
                // 将列表减少为一个文本,包含所有符号
                selected = tickers.reduce((value, element) => value.copyWith(
                      symbol: '${value.symbol}, ${element.symbol}',
                      description: '',
                    ));
              });
            }
          },
        ),
      ],
    );
  }
}

更多关于Flutter股票或行情搜索插件ticker_search的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter股票或行情搜索插件ticker_search的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中使用ticker_search插件来进行股票或行情搜索的代码示例。这个插件允许用户通过股票代码或公司名称来搜索股票信息。

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

dependencies:
  flutter:
    sdk: flutter
  ticker_search: ^latest_version  # 请替换为最新版本号

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

接下来,你可以在你的Flutter应用中实现股票搜索功能。以下是一个简单的示例代码:

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

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

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

class StockSearchScreen extends StatefulWidget {
  @override
  _StockSearchScreenState createState() => _StockSearchScreenState();
}

class _StockSearchScreenState extends State<StockSearchScreen> {
  final TextEditingController _controller = TextEditingController();
  TickerSearchResponse? _response;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stock Search'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                prefixIcon: Icon(Icons.search),
                hintText: 'Search by ticker symbol or company name',
                border: OutlineInputBorder(),
              ),
              onChanged: (value) {
                setState(() {
                  _searchStocks(value);
                });
              },
            ),
            SizedBox(height: 16),
            if (_response != null)
              Expanded(
                child: ListView.builder(
                  itemCount: _response!.data!.length,
                  itemBuilder: (context, index) {
                    final stock = _response!.data![index];
                    return ListTile(
                      title: Text(stock.symbol),
                      subtitle: Text(stock.name),
                      trailing: Text('${stock.price.toDouble().toStringAsFixed(2)}'),
                    );
                  },
                ),
              )
            else
              Center(
                child: CircularProgressIndicator(),
              ),
          ],
        ),
      ),
    );
  }

  void _searchStocks(String query) async {
    try {
      final response = await TickerSearch.search(query);
      setState(() {
        _response = response;
      });
    } catch (e) {
      print('Error searching stocks: $e');
      setState(() {
        _response = null;
      });
    }
  }

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

在这个示例中:

  1. 我们创建了一个StockSearchScreen,它包含一个TextField用于用户输入股票代码或公司名称。
  2. 使用TextEditingController来管理文本字段的状态。
  3. 当用户在文本字段中输入内容时,onChanged回调会触发_searchStocks函数,该函数使用TickerSearch.search方法来搜索股票。
  4. 搜索结果存储在_response变量中,并在UI中显示为一个ListView,其中每个列表项显示股票代码、名称和价格。
  5. 如果搜索过程中发生错误,我们在控制台中打印错误信息,并将_response设置为null

请注意,TickerSearch.search方法可能需要互联网连接,并且搜索结果可能受到API限制和配额的影响。确保在生产环境中处理这些潜在的错误和限制。

回到顶部