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.
Go through the below video tutorial for more in detailed explanation of network call with provider.
pubspec.yaml :
Specify the provider and http dependencies for implementation of flutter network call with provider and also specify the versions according to latest available.
dependencies: flutter: sdk: flutter provider: http:
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:fluter_login_provider/datamodel.dart'; import 'package:fluter_login_provider/main.dart'; import 'package:flutter/material.dart'; class Data extends ChangeNotifier{ late DataModel dataModel; fetchData(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() { // TODO: implement 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(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 :
Providing the full code for network call with provider implementation.
import 'dart:convert'; import 'package:fluter_login_provider/data.dart'; import 'package:fluter_login_provider/datamodel.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:http/http.dart' as http; 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() { // TODO: implement 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(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 Output :
If you have any query in the implementation of network call with provider do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.