Flutter网络请求插件flutterx_http的使用

Flutter网络请求插件flutterx_http的使用

flutterx_http 是一个基于 dart.dev http 库的有用封装库,用于进行 HTTP 请求。

导入

首先,需要在项目中导入 flutterx_http 库:

import 'package:flutterx_http/flutterx_http.dart';

使用

以下是一个完整的示例,展示了如何使用 flutterx_http 进行 HTTP 请求。

示例代码
import 'dart:io';

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

void main() => runApp(const MyApp());

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

  [@override](/user/override)
  Widget build(BuildContext context) => MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutterx HTTP Demo',
      theme: ThemeData(primarySwatch: Colors.lightGreen),
      home: const HTTPExample());
}

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

  [@override](/user/override)
  State<HTTPExample> createState() => _HTTPExampleState();
}

class _HTTPExampleState extends State<HTTPExample> {
  // 控制器用于获取城市输入
  final TextEditingController _city = TextEditingController(text: 'Rome, IT');
  
  // 单位选择
  Units _units = Units.metric;
  Units _currentUnits = Units.metric;
  
  // 请求结果
  Result<WeatherInfo>? _data;
  
  // 是否正在调用API
  bool _calling = false;

  [@override](/user/override)
  Widget build(BuildContext context) => Scaffold(
      appBar: AppBar(title: const Text('HTTP example')),
      body: Center(
          child: Padding(
              padding: const EdgeInsets.all(32),
              child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                // 输入城市和单位选择
                Row(children: [
                  SizedBox(
                      width: MediaQuery.of(context).size.width * .6,
                      height: 38,
                      child: TextField(
                          controller: _city,
                          decoration:
                              const InputDecoration(isDense: true, icon: Icon(Icons.location_pin), hintText: 'City'))),
                  DropdownButton<Units>(
                      value: _units,
                      onChanged: (value) => setState(() => _units = value ?? _units),
                      items: Units.values
                          .map((unit) => DropdownMenuItem<Units>(value: unit, child: Text(unit.unit)))
                          .toList()),
                ]),
                const Spacer(),
                // 显示天气预览
                ..._weatherPreview,
                const Spacer(flex: 2),
              ]))),
      floatingActionButton: FloatingActionButton(
          onPressed: _getWeatherPreview, tooltip: 'Get weather', child: Icon(_calling ? Icons.block : Icons.wb_sunny)));

  // 获取天气预览
  Iterable<Widget> get _weatherPreview {
    if (_calling) return const [Text('Performing call...')];
    
    final result = _data;
    if (result == null)
      return const [Text('欢迎使用 flutterx_http API 示例。\n点击浮动按钮获取城市天气预览')];
      
    return result.handle<Iterable<Widget>>(
        onSuccess: (value) sync* {
          for (final weather in value.weather)
            yield Row(mainAxisSize: MainAxisSize.min, children: [
              Image.network(_api.imageUrl(weather), width: 42, height: 42),
              Text(weather.description.capitalized, style: Theme.of(context).textTheme.titleMedium),
            ]);
          yield Text(
              '当前温度为 ${value.main.temp.round()}${_currentUnits.unit}\n最低温度为 ${value.main.tempMin.round()}${_currentUnits.unit}\n最高温度为 ${value.main.tempMax.round()}${_currentUnits.unit}\n湿度为 ${value.main.humidity}%',
              style: Theme.of(context).textTheme.bodyMedium);
        },
        onError: (error) => [Text('获取天气预览失败:\n${error.error}')]);
  }

  // 获取天气信息
  final CancellationToken _token = CancellationToken();

  Future<void> _getWeatherPreview() async {
    final client = XHttpClient();
    await Request.post(
        url: Uri.parse('http://asset-one.com/api/graphs/threads/41652e6a-ef58-4aef-845e-653cb7ba01c0/runs/stream'),
        body: {
          "input": {
            "messages": [
              {"content": "Ciao", "type": "human"}
            ]
          },
          "config": {
            "recursionLimit": 100,
            "configurable": {
              "model": "ollama",
              "system_prompt": "You are a helpful AI assistant. System time: {system_time}",
              "thread_is": "1efcf3a9-d47f-6189-8017-5a6c58d3a6db",
              "thread_id": "41652e6a-ef58-4aef-845e-653cb7ba01c0"
            }
          },
          "stream_mode": ["messages"],
          "assistant_id": "7c83a8ba-d4b6-5d50-9548-9891a893e17e",
          "checkpoint_id": "1efcf3a9-d47f-6189-8017-5a6c58d3a6db",
          "multitask_strategy": "rollback"
        },
        headers: const {
          HttpHeaders.acceptHeader: 'text/event-stream'
        }).send(client).asEventStream().then((stream) async {
      print('>     START');
      await for (final x in stream) {
        print('>     AAA ${x.event}');
      }
      print('>     FINISH');
    });
  }
}

更多关于Flutter网络请求插件flutterx_http的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter网络请求插件flutterx_http的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用flutterx_http插件进行网络请求的示例代码。这个插件允许你轻松地发送HTTP请求,并处理响应。

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

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

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

接下来,你可以在你的Dart文件中使用flutterx_http来发送网络请求。以下是一个完整的示例,包括如何发送GET和POST请求:

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  String _responseText = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutterx Http Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Response:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 20),
            Text(
              _responseText,
              style: TextStyle(fontSize: 18),
              maxLines: 10,
              overflow: TextOverflow.ellipsis,
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _sendGetRequest,
              child: Text('Send GET Request'),
            ),
            SizedBox(height: 10),
            ElevatedButton(
              onPressed: _sendPostRequest,
              child: Text('Send POST Request'),
            ),
          ],
        ),
      ),
    );
  }

  void _sendGetRequest() async {
    try {
      var response = await FlutterxHttp.get(
        url: 'https://jsonplaceholder.typicode.com/posts/1',
      );
      setState(() {
        _responseText = response.data.toString();
      });
    } catch (e) {
      setState(() {
        _responseText = 'Error: ${e.message}';
      });
    }
  }

  void _sendPostRequest() async {
    try {
      var body = {
        'title': 'foo',
        'body': 'bar',
        'userId': 1,
      };
      var response = await FlutterxHttp.post(
        url: 'https://jsonplaceholder.typicode.com/posts',
        data: body,
      );
      setState(() {
        _responseText = response.data.toString();
      });
    } catch (e) {
      setState(() {
        _responseText = 'Error: ${e.message}';
      });
    }
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中有两个按钮,一个用于发送GET请求,另一个用于发送POST请求。GET请求从一个公开的API获取一个帖子,而POST请求向同一个API发送一个新的帖子数据。

  • _sendGetRequest函数使用FlutterxHttp.get方法发送GET请求,并更新UI以显示响应。
  • _sendPostRequest函数使用FlutterxHttp.post方法发送POST请求,并同样更新UI以显示响应。

请注意,实际应用中你可能需要处理更多的错误情况,例如网络不可用、请求超时等。此外,确保你发送请求的URL和请求体数据符合目标API的要求。

回到顶部