flutter http get request example

dart-create-http-request-examples

Hii Developer in these flutter tutorials we are learning how to make a flutter http get request. HTTP is a network library for mobile Application development to get remote data and show it in our mobile app. There are many types of methods to used connect with the remote. the method like as ( GET,  POST, PUT, PATCH, DELETE ). SO In this flutter example, we discuss the flutter HTTP get request example.

flutter HTTP get request body.

So Let’s make a flutter rest API example with GET Method and flutter HTTP get request body. Start Your Android studio and Make a flutter project. And Add HTTP dependencies. Open your project pubspec.yaml file and add the latest dependencies of HTTP.

PubSpec.yaml file 

dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  http: ^0.13.3

GET data from API in a flutter.

So Let’s make an example for getting API first of add dependencies and get pub. then Clear of main.dart file code. and follow these for fullter get data from remote API.

Main.Dart File Full Source Code

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: HomePage(),
      ),
    );
  }
}

class HomePage extends StatelessWidget {
  final stateManager = HomePageManager();
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        SizedBox(height: 50),
        Center(
          child: Wrap(
            spacing: 50,
            alignment: WrapAlignment.center,
            children: [
              ElevatedButton(
                onPressed: stateManager.makeGetRequest,
                child: Text('GET'),
              ),
             
              ),
            ],
          ),
        ),
        SizedBox(height: 20),
        ValueListenableBuilder<RequestState>(
          valueListenable: stateManager.resultNotifier,
          builder: (context, requestState, child) {
            if (requestState is RequestLoadInProgress) {
              return CircularProgressIndicator();
            } else if (requestState is RequestLoadSuccess) {
              return Expanded(child: SingleChildScrollView(child: Text(requestState.body)));
            } else {
              return Container();
            }
          },
        ),
      ],
    );
  }
}

Add code in your Main dart file in these codes, we create a Button and when I click on these buttons, we call the Get API call.

Create a state_management Dart file.

the next step is to create a dart file with the name of state_managment  in these dart files we create API call requests. And getting a response from API.

state_management dart file Source code

import 'package:flutter/foundation.dart';
import 'package:http/http.dart';

class HomePageManager {
  final resultNotifier = ValueNotifier<RequestState>(RequestInitial());
  static const urlPrefix = 'enter your API base url for api';

  Future<void> makeGetRequest() async {
    resultNotifier.value = RequestLoadInProgress();
    final url = Uri.parse('$urlPrefix/posts');
    Response response = await get(url);
    print('Status code: ${response.statusCode}');
    print('Headers: ${response.headers}');
    print('Body: ${response.body}');
    _handleResponse(response);
  }

  void _handleResponse(Response response) {
    if (response.statusCode >= 400) {
      resultNotifier.value = RequestLoadFailure();
    } else {
      resultNotifier.value = RequestLoadSuccess(response.body);
    }
  }
}

class RequestState {
  const RequestState();
}

class RequestInitial extends RequestState {}

class RequestLoadInProgress extends RequestState {}

class RequestLoadSuccess extends RequestState {
  const RequestLoadSuccess(this.body);
  final String body;
}

class RequestLoadFailure extends RequestState {}

adds these codes in your state_managment file and runs you project for output.

 

 

Facebooktwitterredditpinterestlinkedinmail
Recommended
प्रधानमंत्री ग्रामीण आवास योजना 2021 आवेदन फॉर्म | PMAY Gramin…