Home > Back-end >  Flutter - Refresh widget with button press
Flutter - Refresh widget with button press

Time:07-05

I have an app that pulls quotes from an api and displays it.

I am struggling to get my refresh button to work. When the refresh button is pressed a new quote should load.

The current code I have for the page is:

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

import './Quote.dart';

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

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

// call the API and fetch the response
Future<Quote> fetchQuote() async {
  final response = await http.get(Uri.parse('https://favqs.com/api/qotd'));
  if (response.statusCode == 200) {
    return Quote.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to load Quote');
  }
}

class _QuoteDataState extends State<QuoteData>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  late Future<Quote> quote;
  late Future<List<Quote>> wholeQuotes;
  @override
  void initState() {
    super.initState();
    quote = fetchQuote();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return FutureBuilder<Quote>(
      future: quote,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return SafeArea(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(left: 50.0),
                  child: Text(
                    snapshot.data!.quoteText,
                    style: const TextStyle(
                        fontSize: 30.0,
                        color: Colors.white,
                        fontFamily: 'quoteScript'),
                  ),
                ),
                const SizedBox(
                  height: 20.0,
                ),
                Text(
                  '-${snapshot.data!.quoteAuthor}-',
                  style: const TextStyle(
                      fontSize: 23.0,
                      color: Colors.white,
                      fontFamily: 'quoteScript'),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    //share button
                    IconButton(
                      icon: const Icon(
                        Icons.share,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        Share.share(
                            '${snapshot.data!.quoteText}--${snapshot.data!.quoteAuthor}');
                      },
                    ),
                    //refresh button
                    IconButton(
                      icon: const Icon(
                        Icons.share,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        fetchQuote();
                      },
                    ),
                  ],
                ),
              ],
            ),
          );
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }
        // By default, show a loading spinner.
        return const Center(child: CircularProgressIndicator());
      },
    );
  }
}

How can I get the refresh button to refresh the page and load a new quote from the api and display it?

Any help would be appreciated.

CodePudding user response:

Did you try to use setState under onPressed()? You can do something like:

onPressed: () {

setState(()
                        Share.share(
                            '${snapshot.data!.quoteText}--${snapshot.data!.quoteAuthor}');
                      )},

CodePudding user response:

Reset future using setState.

Future<Quote> quote;
...

IconButton(
...
  onPressed: () {
    setState(() {
      quote = fetchQuote();
    });                        
  },
)
  • Related