Flutter人工智能扫描插件flutter_ai_scanner的使用

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

Flutter人工智能扫描插件flutter_ai_scanner的使用

初始化

首先,你需要在main()函数中初始化插件,并设置API密钥。以下是一个简单的示例:

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

void main() async {
  // 设置AI代理并传入API密钥
  Ai.delegate = const GptAiDelegate(key: 'YOUR_API_KEY_HERE');

  // 发送请求以获取AI处理结果
  final response = await Ai.completions(
    AiCompletionRequest(
      prompt: "i ate one piece medium apple and 2 pieces boiled eggs",
      system: "Following the json schema and provide me only json. if you not found return null.\nSchema: {SCHEMA}",
      schema: {
        "name": "string",
        "total_calories": "double",
        "total_protein": "double",
        "total_fat": "double",
        "total_carbs": "double",
        "ingredients": [
          {
            "name": "string",
            "calories": "double",
            "proteinInGram": "double",
            "fatInGram": "double",
            "carbsInGram": "double",
            "quantity": "int",
            "size": "string",
          }
        ],
      },
      builder: (value) => AiData.from(value),
    ),
  );

  // 打印响应结果
  print(response.choices?.firstOrNull?.message?.data);

  // 启动应用
  runApp(const MyApp());
}

数据模型

以下是用于处理AI返回数据的数据模型类定义:

class AiData {
  final String? name;
  final double? totalCalories;
  final double? totalProtein;
  final double? totalFat;
  final double? totalCarbs;
  final List<AiDataIngredient>? ingredients;

  const AiData({
    this.name,
    this.totalCalories,
    this.totalProtein,
    this.totalFat,
    this.totalCarbs,
    this.ingredients,
  });

  factory AiData.from(Map<String, dynamic> source) {
    return AiData(
      name: source['name'] as String?,
      totalCalories: (source['total_calories'] as num?)?.toDouble(),
      totalProtein: (source['total_protein'] as num?)?.toDouble(),
      totalFat: (source['total_fat'] as num?)?.toDouble(),
      totalCarbs: (source['total_carbs'] as num?)?.toDouble(),
      ingredients: (source['ingredients'] as List<dynamic>?)?
          ?.map((e) => AiDataIngredient.from(e as Map<String, dynamic>))
          .toList(),
    );
  }

  Map<String, dynamic> get source {
    return {
      'name': name,
      'total_calories': totalCalories,
      'total_protein': totalProtein,
      'total_fat': totalFat,
      'total_carbs': totalCarbs,
      'ingredients': ingredients?.map((e) => e.source).toList(),
    };
  }

  [@override](/user/override)
  String toString() => "$AiData($source)";
}

class AiDataIngredient {
  final String? name;
  final double? calories;
  final double? proteinInGram;
  final double? fatInGram;
  final double? carbsInGram;
  final int? quantity;
  final String? size;

  const AiDataIngredient({
    this.name,
    this.calories,
    this.proteinInGram,
    this.fatInGram,
    this.carbsInGram,
    this.quantity,
    this.size,
  });

  factory AiDataIngredient.from(Map<String, dynamic> source) {
    return AiDataIngredient(
      name: source['name'] as String?,
      calories: (source['calories'] as num?)?.toDouble(),
      proteinInGram: (source['proteinInGram'] as num?)?.toDouble(),
      fatInGram: (source['fatInGram'] as num?)?.toDouble(),
      carbsInGram: (source['carbsInGram'] as num?)?.toDouble(),
      quantity: source['quantity'] as int?,
      size: source['size'] as String?,
    );
  }

  Map<String, dynamic> get source {
    return {
      'name': name,
      'calories': calories,
      'proteinInGram': proteinInGram,
      'fatInGram': fatInGram,
      'carbsInGram': carbsInGram,
      'quantity': quantity,
      'size': size,
    };
  }

  [@override](/user/override)
  String toString() => "$AiDataIngredient($source)";
}

完整示例Demo

以下是一个完整的示例,展示了如何使用flutter_ai_scanner插件进行AI扫描:

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

void main() async {
  // 设置AI代理并传入API密钥
  Ai.delegate = const GptAiDelegate(key: 'YOUR_API_KEY_HERE');

  // 发送请求以获取AI处理结果
  final response = await Ai.completions(
    AiCompletionRequest(
      prompt: "i ate one piece medium apple and 2 pieces boiled eggs",
      system: "Following the json schema and provide me only json. if you not found return null.\nSchema: {SCHEMA}",
      schema: {
        "name": "string",
        "total_calories": "double",
        "total_protein": "double",
        "total_fat": "double",
        "total_carbs": "double",
        "ingredients": [
          {
            "name": "string",
            "calories": "double",
            "proteinInGram": "double",
            "fatInGram": "double",
            "carbsInGram": "double",
            "quantity": "int",
            "size": "string",
          }
        ],
      },
      builder: (value) => AiData.from(value),
    ),
  );

  // 打印响应结果
  print(response.choices?.firstOrNull?.message?.data);

  // 启动应用
  runApp(const MyApp());
}

// 数据模型类定义
class AiData {
  final String? name;
  final double? totalCalories;
  final double? totalProtein;
  final double? totalFat;
  final double? totalCarbs;
  final List<AiDataIngredient>? ingredients;

  const AiData({
    this.name,
    this.totalCalories,
    this.totalProtein,
    this.totalFat,
    this.totalCarbs,
    this.ingredients,
  });

  factory AiData.from(Map<String, dynamic> source) {
    return AiData(
      name: source['name'] as String?,
      totalCalories: (source['total_calories'] as num?)?.toDouble(),
      totalProtein: (source['total_protein'] as num?)?.toDouble(),
      totalFat: (source['total_fat'] as num?)?.toDouble(),
      totalCarbs: (source['total_carbs'] as num?)?.toDouble(),
      ingredients: (source['ingredients'] as List<dynamic>?)?
          ?.map((e) => AiDataIngredient.from(e as Map<String, dynamic>))
          .toList(),
    );
  }

  Map<String, dynamic> get source {
    return {
      'name': name,
      'total_calories': totalCalories,
      'total_protein': totalProtein,
      'total_fat': totalFat,
      'total_carbs': totalCarbs,
      'ingredients': ingredients?.map((e) => e.source).toList(),
    };
  }

  [@override](/user/override)
  String toString() => "$AiData($source)";
}

class AiDataIngredient {
  final String? name;
  final double? calories;
  final double? proteinInGram;
  final double? fatInGram;
  final double? carbsInGram;
  final int? quantity;
  final String? size;

  const AiDataIngredient({
    this.name,
    this.calories,
    this.proteinInGram,
    this.fatInGram,
    this.carbsInGram,
    this.quantity,
    this.size,
  });

  factory AiDataIngredient.from(Map<String, dynamic> source) {
    return AiDataIngredient(
      name: source['name'] as String?,
      calories: (source['calories'] as num?)?.toDouble(),
      proteinInGram: (source['proteinInGram'] as num?)?.toDouble(),
      fatInGram: (source['fatInGram'] as num?)?.toDouble(),
      carbsInGram: (source['carbsInGram'] as num?)?.toDouble(),
      quantity: source['quantity'] as int?,
      size: source['size'] as String?,
    );
  }

  Map<String, dynamic> get source {
    return {
      'name': name,
      'calories': calories,
      'proteinInGram': proteinInGram,
      'fatInGram': fatInGram,
      'carbsInGram': carbsInGram,
      'quantity': quantity,
      'size': size,
    };
  }

  [@override](/user/override)
  String toString() => "$AiDataIngredient($source)";
}

// 应用主入口
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Ai Scanner',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: Container(), // 你可以在这里添加你的页面
    );
  }
}

更多关于Flutter人工智能扫描插件flutter_ai_scanner的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter人工智能扫描插件flutter_ai_scanner的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 flutter_ai_scanner 插件的基本代码示例。这个插件允许你在 Flutter 应用中集成人工智能扫描功能,比如二维码扫描、物体识别等。请注意,这个插件的具体功能和可用性可能会随着版本更新而变化,因此请参考最新的官方文档以获取最新信息。

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

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

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

接下来,你可以创建一个简单的 Flutter 应用来使用这个插件。以下是一个基本的代码示例:

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

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

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

class ScannerPage extends StatefulWidget {
  @override
  _ScannerPageState createState() => _ScannerPageState();
}

class _ScannerPageState extends State<ScannerPage> {
  late FlutterAiScannerController _controller;
  String _scanResult = "";

  @override
  void initState() {
    super.initState();
    _controller = FlutterAiScannerController(
      // 配置参数,比如扫描类型等,这里以二维码扫描为例
      barcodeFormats: [BarcodeFormat.qrCode],
      beepOnScan: true, // 扫描成功时发出声音
    );
    _controller.addListener(() {
      if (_controller.isScanned) {
        setState(() {
          _scanResult = _controller.scanResult!;
        });
        _controller.reset(); // 重置扫描器以便进行下一次扫描
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter AI Scanner Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(
              child: FlutterAiScanner(
                controller: _controller,
                scannerAreaColor: Colors.grey[200]!,
                scannerAreaStyle: ScannerAreaStyle(
                  borderColor: Colors.blueAccent,
                  borderWidth: 4.0,
                ),
              ),
            ),
            SizedBox(height: 20),
            Text(
              'Scan Result: $_scanResult',
              style: TextStyle(fontSize: 20),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的 Flutter 应用,其中包含一个扫描页面。这个页面使用 FlutterAiScanner 组件来显示扫描区域,并通过 FlutterAiScannerController 来控制扫描行为。当扫描到二维码时,扫描结果会显示在页面上。

请注意,这个示例仅展示了基本的扫描功能。flutter_ai_scanner 插件可能还支持更多高级功能,如自定义扫描区域、处理不同类型的条形码、以及集成更多的人工智能模型。为了充分利用这些功能,请参考插件的官方文档和示例代码。

回到顶部