Flutter REST API(16)
介绍
在本文中,我们将学习如何在 Flutter 应用程序中集成 REST API。正如我们所知,如今几乎所有应用程序都使用 API 来使用远程数据,对于任何想在 Flutter 中创造自己未来的开发人员来说,本文将是至关重要的一部分。那么,让我们一步一步地了解如何在 Flutter 中集成 REST API。
我们正在使用 HTTP 插件从应用程序调用 REST API。HTTP 将提供 get、post、put 和 read 方法来从远程位置发送和接收数据。
我们在本文中使用了虚拟 REST API 示例 URL。您可以使用您的项目 API。
输出
第1步
第一步也是最基本的步骤是在 Flutter 中创建一个新应用程序。如果你是 Flutter 的初学者,那么你可以查看我的博客Create a first app in Flutter。我创建了一个名为“flutter_rest_api”的应用程序。
第2步
打开项目中的 pubspec.yaml 文件并将以下依赖项添加到其中。
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
http: ^0.12.0+2
第 3 步
创建一个名为“rest_api.dart”的新文件,用于配置 REST API URL 和用于发送和接收数据的函数。以下是应用程序中 REST API 的编程实现。
import 'dart:convert';
import 'package:http/http.dart' as http;
class URLS {
static const String BASE_URL = 'http://dummy.restapiexample.com/api/v1';
}
class ApiService {
static Future<List<dynamic>> getEmployees() async {
// RESPONSE JSON :
// [{
// "id": "1",
// "employee_name": "",
// "employee_salary": "0",
// "employee_age": "0",
// "profile_image": ""
// }]
final response = await http.get('${URLS.BASE_URL}/employees');
if (response.statusCode == 200) {
return json.decode(response.body);
} else {
return null;
}
}
static Future<bool> addEmployee(body) async {
// BODY
// {
// "name": "test",
// "age": "23"
// }
final response = await http.post('${URLS.BASE_URL}/create', body: body);
if (response.statusCode == 200) {
return true;
} else {
return false;
}
}
}
第4步
现在,我们将在我们的应用程序中使用 REST API 方法。我们创建了一个小部件来显示所有员工的列表。打开 main.dart 并实现以下代码。
import 'package:flutter/material.dart';
import 'package:flutter_rest_api/rest_api.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.purple,
),
home: EmployeePage(),
);
}
}
class EmployeePage extends StatefulWidget {
@override
_EmployeePageState createState() => _EmployeePageState();
}
class _EmployeePageState extends State<EmployeePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter REST API'),
),
body: FutureBuilder(
future: ApiService.getEmployees(),
builder: (context, snapshot) {
final employees = snapshot.data;
if (snapshot.connectionState == ConnectionState.done) {
return ListView.separated(
separatorBuilder: (context, index) {
return Divider(
height: 2,
color: Colors.black,
);
},
itemBuilder: (context, index) {
return ListTile(
title: Text(employees[index]['employee_name']),
subtitle: Text('Age: ${employees[index]['employee_age']}'),
);
},
itemCount: employees.length,
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddNewEmployeePage(),
),
);
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
第 5 步
为了添加新员工,我们创建了另一个名为 AddNewEmployeePage 的页面,它将向列表中添加一个新员工。以下是实现;为此,我在 main.dart 文件中创建了一个小部件。
class AddNewEmployeePage extends StatefulWidget {
AddNewEmployeePage({Key key}) : super(key: key);
_AddNewEmployeePageState createState() => _AddNewEmployeePageState();
}
class _AddNewEmployeePageState extends State<AddNewEmployeePage> {
final _employeeNameController = TextEditingController();
final _employeeAge = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('New Employee'),
),
body: Center(
child: Padding(
padding: EdgeInsets.all(10),
child: Column(
children: <Widget>[
TextField(
controller: _employeeNameController,
decoration: InputDecoration(hintText: 'Employee Name'),
),
TextField(
controller: _employeeAge,
decoration: InputDecoration(hintText: 'Employee Age'),
keyboardType: TextInputType.number,
),
RaisedButton(
child: Text(
'SAVE',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.purple,
onPressed: () {
final body = {
"name": _employeeNameController.text,
"age": _employeeAge.text,
};
ApiService.addEmployee(body).then((success) {
if (success) {
showDialog(
builder: (context) => AlertDialog(
title: Text('Employee has been added!!!'),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
_employeeNameController.text = '';
_employeeAge.text = '';
},
child: Text('OK'),
)
],
),
context: context,
);
return;
}else{
showDialog(
builder: (context) => AlertDialog(
title: Text('Error Adding Employee!!!'),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('OK'),
)
],
),
context: context,
);
return;
}
});
},
)
],
),
),
),
);
}
}
第 6 步
太好了,您已完成 Flutter REST API 集成。在设备或模拟器中运行此项目并检查输出。
结论
在本文中,我们学习了如何在 Flutter 中实现 REST API。我们已经使用了 HTTP 插件的 get 和 post 方法。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!