Dart与Flutter教程 REST API交互实战

Dart与Flutter教程 REST API交互实战

3 回复

学Dart基础,再学Flutter框架,接着实践调用REST API,建议跟着网课一步步来。

更多关于Dart与Flutter教程 REST API交互实战的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


推荐《Flutter权威指南》,里面有详细REST API交互案例,通俗易懂。

在Flutter中,使用Dart语言与REST API进行交互是非常常见的需求。以下是一个简单的实战教程,展示如何在Flutter中通过HTTP请求与REST API进行交互。

1. 添加依赖

首先,在pubspec.yaml文件中添加http依赖:

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.3

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

2. 创建HTTP请求

接下来,创建一个函数来发送HTTP请求并处理响应。以下是一个简单的GET请求示例:

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

Future<void> fetchData() async {
  final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));

  if (response.statusCode == 200) {
    // 请求成功,解析JSON数据
    List<dynamic> data = jsonDecode(response.body);
    print(data);
  } else {
    // 请求失败,打印错误信息
    print('Failed to load data');
  }
}

3. 在Flutter中使用

你可以在Flutter的initState方法中调用fetchData函数,或者在按钮的onPressed事件中调用它:

import 'package:flutter/material.dart';

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('REST API Example'),
        ),
        body: Center(
          child: ElevatedButton(
            onPressed: fetchData,
            child: Text('Fetch Data'),
          ),
        ),
      ),
    );
  }
}

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

4. 处理POST请求

如果你需要发送POST请求,可以使用以下代码:

Future<void> postData() async {
  final response = await http.post(
    Uri.parse('https://jsonplaceholder.typicode.com/posts'),
    headers: <String, String>{
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode(<String, String>{
      'title': 'foo',
      'body': 'bar',
      'userId': '1',
    }),
  );

  if (response.statusCode == 201) {
    // 请求成功,解析JSON数据
    Map<String, dynamic> data = jsonDecode(response.body);
    print(data);
  } else {
    // 请求失败,打印错误信息
    print('Failed to post data');
  }
}

5. 错误处理

在实际应用中,你可能需要处理网络错误或超时。可以使用try-catch来捕获异常:

Future<void> fetchData() async {
  try {
    final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')).timeout(Duration(seconds: 5));

    if (response.statusCode == 200) {
      List<dynamic> data = jsonDecode(response.body);
      print(data);
    } else {
      print('Failed to load data');
    }
  } catch (e) {
    print('Error: $e');
  }
}

总结

通过以上步骤,你可以在Flutter中使用Dart与REST API进行交互。你可以根据需要扩展这些代码,例如添加更多的HTTP方法(PUT、DELETE等),或者使用更复杂的错误处理逻辑。

回到顶部