get new data with the provider and pull_to_refresh

Issue

I’m making a random quote application that I took from the API and returned a json, the API that I use will generate a new quote when it is refreshed

I implemented it with DART in a flutter app project, the data sent from the public is captured and processed with http and provider.

I want to add a refresh feature to the application and I use pull_to_refresh after I implement it doesn’t work, here we should get a new quote but the quote hasn’t changed,

then how to overcome this, when I do a pull down to refresh and after the refresh is finished the old data is replaced with new data

My HomePage Code

import 'package:myquotes/providers/test_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  @override
  void initState() {
    super.initState();
    Provider.of<TestingProvider>(context, listen: false).getTestingProvider();
  }

  @override
  Widget build(BuildContext context) {

    var test = Provider.of<TestingProvider>(context).test;

    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.teal,
    ));

    RefreshController _refreshController =
      RefreshController(initialRefresh: false);

    void _onRefresh() async{
      // monitor network fetch
      await Future.delayed(Duration(milliseconds: 1000));
      // if failed,use refreshFailed()
      _refreshController.refreshCompleted();
    }

    void _onLoading() async{
      // monitor network fetch
      await Future.delayed(Duration(milliseconds: 1000));

      var newTest = Provider.of<TestingProvider>(context).test;

      // if failed,use loadFailed(),if no data return,use LoadNodata()
      setState(() {
        test = newTest;
      });
      _refreshController.loadComplete();
    }

    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(15),
        child: SmartRefresher(
          header: WaterDropMaterialHeader(),
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoading,
          child: ListView(
            children: <Widget>[
              Column(
                children: <Widget>[
                  Card (
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Center (
                          child: Text(test != null ? "${test.quote.body}" : "No Data !!!"),
                        )
                      ],
                    ),
                  ),
                ]
              ),
            ]
          ),
        ),
      )
    );
  }

}

My TestingProvider

import 'package:myquotes/models/test_model.dart';
import 'package:myquotes/services/api_services.dart';
import 'package:flutter/foundation.dart';

class TestingProvider with ChangeNotifier {
  var api = ApiServices();
  MyTesting test;

    Future<MyTesting> getTestingProvider() async {
    final response = await api.client.get("${api.testUrl}/api/qotd/");
    if (response.statusCode == 200) {
      notifyListeners();
      var res = myTestingFromJson(response.body);
      test = res;
      return res;
    } else {
      return null;
    }
  }

}

Model

import 'dart:convert';

MyTesting myTestingFromJson(String str) => MyTesting.fromJson(json.decode(str));

String myTestingToJson(MyTesting data) => json.encode(data.toJson());

class MyTesting {
    DateTime qotdDate;
    Quote quote;

    MyTesting({
        this.qotdDate,
        this.quote,
    });

    factory MyTesting.fromJson(Map<String, dynamic> json) => MyTesting(
        qotdDate: DateTime.parse(json["qotd_date"]),
        quote: Quote.fromJson(json["quote"]),
    );

    Map<String, dynamic> toJson() => {
        "qotd_date": qotdDate.toIso8601String(),
        "quote": quote.toJson(),
    };
}

class Quote {
    int id;
    bool dialogue;
    bool private;
    List<String> tags;
    String url;
    int favoritesCount;
    int upvotesCount;
    int downvotesCount;
    String author;
    String authorPermalink;
    String body;

    Quote({
        this.id,
        this.dialogue,
        this.private,
        this.tags,
        this.url,
        this.favoritesCount,
        this.upvotesCount,
        this.downvotesCount,
        this.author,
        this.authorPermalink,
        this.body,
    });

    factory Quote.fromJson(Map<String, dynamic> json) => Quote(
        id: json["id"],
        dialogue: json["dialogue"],
        private: json["private"],
        tags: List<String>.from(json["tags"].map((x) => x)),
        url: json["url"],
        favoritesCount: json["favorites_count"],
        upvotesCount: json["upvotes_count"],
        downvotesCount: json["downvotes_count"],
        author: json["author"],
        authorPermalink: json["author_permalink"],
        body: json["body"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "dialogue": dialogue,
        "private": private,
        "tags": List<dynamic>.from(tags.map((x) => x)),
        "url": url,
        "favorites_count": favoritesCount,
        "upvotes_count": upvotesCount,
        "downvotes_count": downvotesCount,
        "author": author,
        "author_permalink": authorPermalink,
        "body": body,
    };
}

Main.dart

import 'package:myquotes/providers/test_provider.dart';
import 'package:myquotes/screens/home_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() => runApp(
    MultiProvider (
      providers: [
        ChangeNotifierProvider(create: (_) => TestingProvider()),
      ], child: MyApp(),
    )
);

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Testing App',
      theme: ThemeData(
        primarySwatch: Colors.teal,
      ),
      home: HomePage(),
    );
  }
}

Solution

Just check this change that i have made

void _onRefresh() async {
      // monitor network fetch
      await Future.delayed(Duration(milliseconds: 1000));
       Provider.of<TestingProvider>(context, listen: false).getTestingProvider();

      // if failed,use refreshFailed()
      _refreshController.refreshCompleted();
    }

Let me know if it works.

Answered By – Sagar Acharya

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *