Flutter开发的手机App如何显示百度AI提问的内容

我正在用Flutter开发一个手机App,需要集成百度AI的问答功能。请问如何将百度AI返回的提问内容显示在App界面上?具体需要调用哪些API或使用什么插件?能否提供一个简单的代码示例?

2 回复

使用Flutter调用百度AI API获取数据后,通过FutureBuildersetState更新UI,将返回内容显示在TextListView等组件中。

更多关于Flutter开发的手机App如何显示百度AI提问的内容的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中显示百度AI的提问内容,主要涉及网络请求和数据展示。以下是实现步骤:

1. 添加依赖

pubspec.yaml 中添加:

dependencies:
  http: ^0.13.4

2. 网络请求封装

创建API服务类调用百度AI接口:

import 'dart:convert';
import 'package:http/http.dart' as http;

class BaiduAIService {
  static const String _apiKey = '你的API_KEY';
  static const String _secretKey = '你的SECRET_KEY';
  static String _accessToken = '';

  // 获取访问令牌
  static Future<void> _getAccessToken() async {
    final response = await http.post(
      Uri.parse('https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=$_apiKey&client_secret=$_secretKey'),
    );
    if (response.statusCode == 200) {
      _accessToken = jsonDecode(response.body)['access_token'];
    }
  }

  // 发送提问请求
  static Future<String> sendQuestion(String question) async {
    if (_accessToken.isEmpty) await _getAccessToken();
    
    final response = await http.post(
      Uri.parse('https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=$_accessToken'),
      headers: {'Content-Type': 'application/json'},
      body: jsonEncode({
        'messages': [{'role': 'user', 'content': question}]
      }),
    );
    
    if (response.statusCode == 200) {
      return jsonDecode(response.body)['result'];
    }
    return '请求失败: ${response.statusCode}';
  }
}

3. UI界面实现

import 'package:flutter/material.dart';

class AIQuestionPage extends StatefulWidget {
  @override
  _AIQuestionPageState createState() => _AIQuestionPageState();
}

class _AIQuestionPageState extends State<AIQuestionPage> {
  final TextEditingController _controller = TextEditingController();
  String _response = '';

  void _sendQuestion() async {
    final response = await BaiduAIService.sendQuestion(_controller.text);
    setState(() {
      _response = response;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('百度AI问答')),
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              controller: _controller,
              decoration: InputDecoration(
                hintText: '输入您的问题',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _sendQuestion,
              child: Text('发送问题'),
            ),
            SizedBox(height: 20),
            Expanded(
              child: SingleChildScrollView(
                child: Text(_response),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

4. 重要说明

  • 需要在百度AI平台申请API Key和Secret Key
  • 实际使用时需要处理加载状态和错误情况
  • 建议添加请求超时和重试机制
  • 对于长文本响应,建议使用SelectableText支持文本选择

5. 权限配置

android/app/src/main/AndroidManifest.xml 中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

这样就能实现基本的百度AI问答功能,用户输入问题后,App会显示百度AI返回的回答内容。

回到顶部