Flutter network call with provider | Fetch Data | GET

 

Flutter network call with provider :

Flutter network call with provider implementation is explained in this part of the tutorial.In our previous blogs we have covered tutorial on provider.

Making use of provider will make it easier for you handle data within your app i.e., you can provide data that can be consumed in any screen and also updates too.

We can have multiple providers in our app which will make data available based on the type to its descendants  so that we can easily distinguish the data.

All the listeners or consumers will receive the data once the notifyListeners is been called.Provider pattern is recommended by flutter team as it avoids a lot of boilerplate code.

 

Flutter network call with provider video tutorial :

Watch the video tutorial below for a detailed explanation of network calls with Provider.

 

pubspec.yaml :

Specify the latest versions of the provider and http dependencies for implementing Flutter network calls with Provider.

dependencies:
  flutter:
    sdk: flutter
  provider: ^5.0.0
  http: ^0.13.3

 

 

datamodel :

We are specifying a datamodel class which has these variables id, userId and title which we fetch from the api.

class DataModel {
  final int id;
  final int userId;
  final String title;

  DataModel({
    required this.id,
    required this.userId,
    required this.title,
  });

  factory DataModel.fromJson(Map<String, dynamic> json) {
    return DataModel(
      id: json['id'],
      userId: json['userId'],
      title: json['title'],
    );
  }
}

 



data :

With the help of this data class extending ChangeNotifier  we will make us of provider pattern by calling up a flutter network call with provider  and providing data across app.

import 'package:flutter_login_provider/datamodel.dart';
import 'package:flutter_login_provider/main.dart';
import 'package:flutter/material.dart';

class Data extends ChangeNotifier {
  late DataModel dataModel;

  fetchData(BuildContext context) async {
    dataModel = await getData(context);
    notifyListeners();
  }
}

 

 

main.dart :

We have initialized the void main and specified MultiProvider and provided type to be Data to make flutter network call with provider.

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider<Data>(
          create: (_) => Data(),
        ),
      ],
      child: MyApp(),
    ),
  );
}

 

 

In init state we have made the network call with the help of provider.

@override
void initState() {
  super.initState();
  final data = Provider.of<Data>(context, listen: false);
  data.fetchData(context);
}

 

 

Populated the data received through network call into a text field as below.

Center(child: Container(child: Text(data.dataModel.title))),

 

 

Declaring the network call implementation by making use of which we received the data and stored into dataModel thereafter providing it to required listeners.

Future<DataModel> getData(BuildContext context) async {
  late DataModel dataModel;
  try {
    final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      dataModel = DataModel.fromJson(data);
    } else {
      print("Something went wrong");
    }
  } catch (e) {
    print(e.toString());
  }
  return dataModel;
}

 

 

Flutter network call with provider Full Code :

Here’s the full code for implementing network calls with Provider in Flutter

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

import 'data.dart';
import 'datamodel.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider<Data>(
          create: (_) => Data(),
        ),
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  void initState() {
    super.initState();
    final data = Provider.of<Data>(context, listen: false);
    data.fetchData(context);
  }

  @override
  Widget build(BuildContext context) {
    final data = Provider.of<Data>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text("Provider Network Call"),
      ),
      body: Center(
        child: Container(
          child: Text(data.dataModel.title),
        ),
      ),
    );
  }
}

Future<DataModel> getData(BuildContext context) async {
  late DataModel dataModel;

  try {
    final response = await http.get(
        Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));

    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      dataModel = DataModel.fromJson(data);
    } else {
      print("Something went wrong");
    }
  } catch (e) {
    print(e.toString());
  }

  return dataModel;
}

 

 

Output :

flutter network call with provider

If you have any questions about implementing network calls with Provider, feel free to ask in the comments below. If you found this tutorial helpful, please like and share for more informative updates.

Show Buttons
Hide Buttons
Read previous post:
Flutter login with Provider
Flutter Login with Provider: Seamless User Authentication Implementation

Flutter login with Provider : In a Flutter app, the UI mirrors the current state of the application. Any changes...

Close