Flutter provider post network call implementation | Post

 

Flutter Provider Post :

We make network calls much frequently in our apps so knowing about the usage and implementation is must so let’s get started with this tutorial on Flutter Provider Post.

Using provider will make our work much easy in-terms of state management, we use to handle state in flutter apps.

Provider makes it easy for app development by separating business logic and also makes it easier to use the data through out the app.

We will try to create data i.e., send data using a Flutter provider POST call.

 

Flutter Provider Post :

Go through the below tutorial for more details on implementation.

 

pubspec.yaml :

Let us add the required dependencies like provider and http with their latest available version numbers to avoid the code level issues.

dependencies:
  flutter:
    sdk: flutter
  provider: 
  http:

 

data.dart :

We have created a Data class extending a Change Notifier where we provide the sendData method which will accept context, title and userId.

This class is of a type async where we wait till we get response and update with the help of notify listeners.

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;

  sendData(context, title, userId) async{

    dataModel = await postData(context, title, userId);

    notifyListeners();
  }
}

 

datamodel.dart :

DataModel class provides the required key variables to be parsed with the api and print on to the screen. Here we are fetching the values and storing.

class DataModel {
  final int id;
  final String 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']);
  }
}

main.dart :

Let us initialize with void main() and add multi provider for Flutter Provider Post.

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

 

Add controllers to fetch the data from the input fields

var titleController = TextEditingController();
var userIdController = TextEditingController();

 

Add text input fields and button to make user interface to accept the data. Inside the onPressed() specify the sendData().

data.sendData(context, titleController.text.toString(),
    userIdController.text.toString());

 

Specify the body i.e., data to be sent through api using dataInput variable.

var dataInput = {"title": title, "userId": userId};

Api to be parsed

Uri.parse("https://jsonplaceholder.typicode.com/posts"),

 

Add a header

headers: {"Content-type": "application/x-www-form-urlencoded"},

 

Specify the encoding

encoding: convert.Encoding.getByName("utf-8"),

 

Now add body

body: dataInput

 

final response = await http.post(
    Uri.parse("https://jsonplaceholder.typicode.com/posts"),
    headers: {"Content-type": "application/x-www-form-urlencoded"},
    encoding: convert.Encoding.getByName("utf-8"),
    body: dataInput);

 

Process the data according to the success and failure

if (response.statusCode == 201) {

  print(response.statusCode);
  print(response.body);

  return DataModel.fromJson(convert.json.decode(response.body));
}else{
  throw Exception('Something went wrong');
}

We have made use of the imports like http, convert as below

import 'package:http/http.dart' as http;
import 'dart:convert' as convert;

 

Providing the full code for integration of Flutter Provider Post.

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;
import 'dart:convert' as convert;

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
  Widget build(BuildContext context) {
    final data = Provider.of<Data>(context);

    var titleController = TextEditingController();
    var userIdController = TextEditingController();

    return Scaffold(
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(20.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                decoration: InputDecoration(hintText: 'Enter title'),
                controller: titleController,
              ),
              TextField(
                decoration: InputDecoration(hintText: 'Enter userId'),
                controller: userIdController,
              ),
              TextButton(
                  onPressed: () {
                    data.sendData(context, titleController.text.toString(),
                        userIdController.text.toString());
                  },
                  child: Text('Submit'))
            ],
          ),
        ),
      ),
    );
  }
}

Future<DataModel> postData(BuildContext context, String title, String userId) async {
  var dataInput = {"title": title, "userId": userId};

  final response = await http.post(
      Uri.parse("https://jsonplaceholder.typicode.com/posts"),
      headers: {"Content-type": "application/x-www-form-urlencoded"},
      encoding: convert.Encoding.getByName("utf-8"),
      body: dataInput);
  if (response.statusCode == 201) {

    print(response.statusCode);
    print(response.body);

    return DataModel.fromJson(convert.json.decode(response.body));
  }else{
    throw Exception('Something went wrong');
  }
}

 

Flutter Provider Post Output :

Flutter Provider Post

 

If you have any query’s in this tutorial for Flutter Provider Post do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.

Show Buttons
Hide Buttons
Read previous post:
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...

Close