Flutter政府FBI接口集成插件dart_gov_fbi的使用

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

Flutter政府FBI接口集成插件dart_gov_fbi的使用

Three screenshots from the example program.

Empower your Dart applications with seamless access to critical information from the Federal Bureau of Investigation (FBI) using the DartGov FBI SDK. This powerful software development kit provides developers with a straightforward interface to communicate with the FBI’s public APIs, specifically tailored for accessing data on wanted persons and art crimes.

Installation

In the pubspec.yaml of your project, add the following dependency:

dependencies:
  dart_gov_fbi: ^0.1.1

Import it to each file you use it in:

import 'package:dart_gov_fbi/dart_gov_fbi.dart';

Usage

The FBI’s database can only be accessed in chunks. Rather than dumping the entire thing into your program, you will need to decide how you want to access the information, and what you are looking for.

The database is broken up into pages, which you can access by index (starting at 1). By default, the pages are 50 items in length. That means with 1000 items, the database will have 20 pages.

You can further refine your search by changing the page size, or the number of items per page. Let’s say you change the page size to 10 (instead of 50). Now the same database with 1000 items will have 100 pages (instead of 20). The data is the same, what changes is how it is packaged up and sent to you. This means that with a page size of 10, pages 1 - 5 will have the same data as page 1 when using a page size of 50.

Warning: If you try and access their database too many times in a short time span, they will lock you out for a while. Only pull what you need, or risk triggering their CloudFlare lockout.

Example 1 - Fetching a page of data

This example shows a few ways to fetch a single page of data.

// Fetch page 1 with page size 50
fetchArtCrimes(); // Art crimes
fetchWantedPersons(); // Wanted persons

// Fetch page 3 with page size 50
fetchArtCrimes(page: 3); // Art crimes
fetchWantedPersons(page: 3); // Wanted persons

// Fetch page 3 with page size 25
fetchArtCrimes(page: 3, pageSize: 25); // Art crimes
fetchWantedPersons(page: 3, pageSize: 25); // Wanted persons

// Fetch the last page by reversing the order
fetchArtCrimes(
  sortDirection = ArtCrimeSortDirection.ascending,
);
fetchWantedPersons(
  sortDirection = WantedPersonSortDirection.ascending,
);

Example 2 - Fetch specific item

If you already have the ID of an item you want, you can directly fetch that item from the database.

fetchArtCrime('artCrimeId_123'); // Art crime
fetchWantedPerson('wantedPersonId_123'); // Wanted person

Complete Demo Example

Below is a complete demo application that fetches wanted persons data and displays it in a Flutter app.

import 'dart:math';

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

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}

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

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  /// The future that fetches the wanted persons.
  final Future<WantedPersonResultSet> wantedPersonsFuture = fetchWantedPersons(
    page: Random().nextInt(10) + 1,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('DartGov FBI Demo'),
        backgroundColor: Colors.black,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () {
              setState(() {});
            },
          ),
        ],
      ),
      body: FutureBuilder(
        future: wantedPersonsFuture,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data != null && snapshot.data is WantedPersonResultSet) {
              final WantedPersonResultSet results = snapshot.data as WantedPersonResultSet;

              if (results.wantedPersons != null && results.wantedPersons!.isNotEmpty) {
                final int max = results.wantedPersons!.length - 1;
                final int index = Random().nextInt(max + 1);

                final WantedPerson person = results.wantedPersons![index];

                return _wantedPoster(context, person);
              }
            }

            return const Text('Error!');
          } else if (snapshot.hasError) {
            return const Text('Error!');
          }
          return const CircularProgressIndicator();
        },
      ),
    );
  }

  /// The randomly generated wanted poster.
  Widget _wantedPoster(BuildContext context, WantedPerson person) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _header(context),

          const SizedBox(height: 15),

          Text(
            person.title ?? '',
            style: Theme.of(context).textTheme.headlineSmall?.copyWith(color: Colors.red),
            textAlign: TextAlign.center,
          ),

          const SizedBox(height: 15),

          Text(
            person.description ?? '',
            style: Theme.of(context).textTheme.titleMedium?.copyWith(color: Colors.red),
            textAlign: TextAlign.center,
          ),

          const SizedBox(height: 15),

          _image(context, person.images),

          _infoBlock('DESCRIPTION', _table(context, person)),

          _infoBlock('REWARD', person.rewardText),

          _infoBlock('REMARKS', person.remarks),

          _infoBlock('CAUTION', person.caution),

          _infoBlock('DETAILS', person.details),
        ],
      ),
    );
  }

  /// The red header with the FBI logo and title.
  Widget _header(BuildContext context) {
    return Container(
      color: Colors.red,
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      child: Row(
        children: [
          Image.asset(
            'assets/images/fbi_logo.png',
            height: 75,
          ),

          const SizedBox(width: 10),

          Flexible(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'WANTED',
                  style: Theme.of(context).textTheme.headlineMedium?.copyWith(color: Colors.white),
                ),
                Text(
                  'BY THE FBI',
                  style: Theme.of(context).textTheme.headlineMedium?.copyWith(color: Colors.white),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// The image(s) of the wanted person.
  Widget _image(BuildContext context, List<FbiImage>? images) {
    if (images == null || images.isEmpty) {
      return const SizedBox();
    }

    List<Widget> imageWidgets = [];

    for (int i = 0; i < min(3, images.length); i++) {
      imageWidgets.add(Image.network(
        images[i].thumbUrl ?? '',
        height: 125,
      ));
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: imageWidgets,
      ),
    );
  }

  /// Each information block with a title and information.
  Widget _infoBlock(String title, dynamic value) {
    Widget valueWidget;

    if (value is Widget) {
      valueWidget = value;
    } else if (value is String) {
      valueWidget = _infoBlockText(value);
    } else if (value is List<String>) {
      valueWidget = _infoBlockText(value.join(', '));
    } else {
      return const SizedBox();
    }

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 10),
      child: Column(
        children: [
          const SizedBox(height: 5),
          Text(
            title,
            style: Theme.of(context).textTheme.titleMedium?.copyWith(color: Colors.red),
          ),
          const SizedBox(height: 5),
          valueWidget,
        ],
      ),
    );
  }

  /// A helper method for [_infoBlock] to create a text widget.
  Widget _infoBlockText(String text) {
    return Text(
      text,
      style: Theme.of(context).textTheme.bodySmall,
    );
  }

  /// The table that contains information about the wanted person.
  Widget _table(BuildContext context, WantedPerson person) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _tableCell(context, 'Aliases', person.aliases?.join(', ') ?? ''),
        _tableCell(context, 'Date(s) of Birth Used', person.datesOfBirthUsed?.join(', ') ?? '', false),
        _tableCell(context, 'Place of Birth', person.placeOfBirth ?? ''),
        _tableCell(context, 'Hair', person.hairColor ?? '', false),
        _tableCell(context, 'Eyes', person.eyeColor ?? ''),
        _tableCell(context, 'Height', person.heightFeetText ?? '', false),
        _tableCell(context, 'Weight', person.weightLbsText ?? ''),
        _tableCell(context, 'Sex', person.sex ?? '', false),
        _tableCell(context, 'Race', person.race ?? ''),
        _tableCell(context, 'Nationality', person.nationality ?? '', false),
        _tableCell(context, 'Scars and Marks', person.scarsAndMarks ?? ''),
      ],
    );
  }

  /// A helper method for [_table] to create a table cell.
  Widget _tableCell(BuildContext context, String title, String value, [bool isGrey = true]) {
    return Container(
      color: isGrey ? Colors.grey[300] : null,
      padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '$title: ',
            style: Theme.of(context).textTheme.bodySmall?.copyWith(fontWeight: FontWeight.bold),
          ),
          Flexible(
            child: Text(
              value,
              softWrap: true,
              style: Theme.of(context).textTheme.bodySmall,
            ),
          ),
        ],
      ),
    );
  }
}

If you found this helpful, please consider donating. Thanks!

buy me a coffee      paypal      venmo


更多关于Flutter政府FBI接口集成插件dart_gov_fbi的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter政府FBI接口集成插件dart_gov_fbi的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中集成并使用dart_gov_fbi插件的示例代码。请注意,dart_gov_fbi是一个假设的插件名称,因为实际上并没有一个名为dart_gov_fbi的官方或广泛使用的Flutter插件。然而,我会提供一个通用的模板,展示如何集成和使用一个假设的政府FBI接口插件。

首先,确保你已经在pubspec.yaml文件中添加了该插件的依赖项(这里使用假设的插件名和版本号):

dependencies:
  flutter:
    sdk: flutter
  dart_gov_fbi: ^1.0.0  # 假设的版本号

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

接下来,在你的Flutter应用中,你可以按照以下方式使用这个插件。以下是一个简单的示例,展示如何初始化插件并调用一个假设的FBI接口方法:

import 'package:flutter/material.dart';
import 'package:dart_gov_fbi/dart_gov_fbi.dart';  // 假设的插件导入路径

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  String result = '';

  @override
  void initState() {
    super.initState();
    // 初始化插件并调用FBI接口方法
    _fetchFBIData();
  }

  Future<void> _fetchFBIData() async {
    try {
      // 假设的FBI插件实例化和方法调用
      FbiApi fbiApi = FbiApi();
      var data = await fbiApi.getSomeData();  // 假设的方法名
      setState(() {
        result = data.toString();  // 假设返回的数据是某种对象,这里转为字符串显示
      });
    } catch (e) {
      setState(() {
        result = 'Error: ${e.message}';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('FBI API Integration Demo'),
      ),
      body: Center(
        child: Text(result),
      ),
    );
  }
}

// 假设的FBI API插件类定义(实际使用时,请参考插件的官方文档)
class FbiApi {
  // 假设的异步方法,用于获取FBI数据
  Future<dynamic> getSomeData() async {
    // 这里应该是实际的网络请求或数据获取逻辑
    // 由于这是一个示例,所以直接返回一个模拟的数据对象
    return {
      'status': 'success',
      'data': {
        'caseNumber': '123456',
        'description': 'This is a sample case description.',
      },
    };
  }
}

请注意,上面的FbiApi类是一个假设的实现,仅用于展示如何定义一个插件类并调用其方法。在实际应用中,你应该参考dart_gov_fbi插件的官方文档来了解如何正确初始化插件并调用其提供的API方法。

由于dart_gov_fbi是一个假设的插件名称,因此你需要找到实际的政府FBI接口插件(如果存在的话),并按照其文档进行集成和使用。如果这样的插件不存在,你可能需要通过HTTP请求直接访问FBI提供的API接口,并使用httpdio等Flutter网络请求库来处理这些请求。

回到顶部