Flutter network calls with providers:
Calling the Flutter network through a provider implementation is covered in this part of the tutorial. In a previous blog we covered a tutorial. producer.
Providers make it easier to process data within your app. This means it can also provide data and updates that can be used on any screen.
You can include multiple providers in your app to make it easy to differentiate between data.
Any listener or consumer will receive data when notifyListeners is called. The flutter team recommends the provider pattern because it avoids a lot of boilerplate code.
pubspec.yaml :
You specify the provider and http dependencies, and also version according to the latest available version.
dependencies: flutter: sdk: flutter provider: http:
Data model:
I’m specifying a data model class with id, userId and title variables 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 that extends ChangeNotifier, we will create the provider pattern by invoking a flutter network call with the provider and providing data throughout the 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 Darts:
We initialize a void main, specify a MultiProvider, and provide a data type so that we can make Provider and flutter network calls.
void main() { runApp(MultiProvider( providers: [ChangeNotifierProvider<Data>(create: (_) => Data())], child: MyApp(), )); }
A network call was made with the help of the provider in the initialization state.
@override void initState() { // TODO: implement initState super.initState(); final data = Provider.of<Data>(context, listen: false); data.fetchData(context); }
I have filled the text fields with data received via network call as shown below.
Center(child: Container(child: Text(data.dataModel.title))),
Declare the implementation of the network call by receiving the data, storing it in the dataModel, and providing it to the listeners it needs.
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; }
It provides the full code for calling the flutter network along with the 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; }
Print:
If you have a query about implementing a flutter network call with your provider, let us know in the comments section below. If you like this tutorial, please like and share us for more interesting updates.