📜  Fluttter http get - TypeScript (1)

📅  最后修改于: 2023-12-03 15:00:49.308000             🧑  作者: Mango

Flutter Http Get - TypeScript

If you are a developer who works with both Flutter and TypeScript, you may need to make HTTP requests from your Flutter app to a TypeScript server. In this guide, we will go over how to make an HTTP GET request to a TypeScript server from a Flutter app using the http package.

Prerequisites

Before we begin, make sure you have Flutter and TypeScript installed on your machine. You should also have a TypeScript server set up with an endpoint that responds to GET requests.

Setting Up the Flutter App
  1. Open your Flutter project and add the http package to your dependencies in your pubspec.yaml file:
dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.4
  1. Run flutter pub get in your terminal to download the http package.
Making the Http GET Request
  1. Import the http package:
import 'package:http/http.dart' as http;
  1. Define an async function to make the GET request:
Future<void> getData() async {
  final response = await http.get(Uri.parse('http://localhost:3000/data'));
  if (response.statusCode == 200) {
    // handle successful response
  } else {
    // handle error
  }
}

Here, we are making a GET request to the http://localhost:3000/data endpoint. If the response status code is 200, we know that we have received a successful response and can handle the response data accordingly. If the status code is not 200, we should handle the error.

Handling the Response Data

To handle the response data, we can use the response.body property of the http.Response object, which contains the body of the response as a string.

final response = await http.get(Uri.parse('http://localhost:3000/data'));
if (response.statusCode == 200) {
  final data = response.body;
  // handle data
} else {
  // handle error
}

If the response data is in JSON format, we can use the json.decode() method to convert it to a Map or List object.

final response = await http.get(Uri.parse('http://localhost:3000/data'));
if (response.statusCode == 200) {
  final data = json.decode(response.body);
  // handle data
} else {
  // handle error
}
Conclusion

Making HTTP GET requests from a Flutter app to a TypeScript server is relatively easy using the http package. By following the steps outlined in this guide, you should be able to successfully make GET requests and handle the response data in your Flutter app.