简体   繁体   中英

How to update the initial state on Flutter

I'm building a flutter page that shows to the users a list of the credit cards that are stored on the back-end and lets the user delete already existing cards.

To fetch the cards from the back-end I'm using initState() . Note that controller.getCreditCards() returns a Future<List<CreditCardSummary>> :

  @override
  void initState() {
    super.initState();
    _futureCreditCards = controller.getCreditCards();
  }

This List is then rendered using a FutureBuilder , just like the documentation recommends:

  Widget build(BuildContext context) {
    return FutureBuilder<List<CreditCardSummary>>(
        future: _futureCreditCards,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return Scaffold(
              // My page that renders all the cards goes here
              // Inside this future builder I can access the cards list with snapshot.data
            );
          } else if (snapshot.hasError) {
            return Text('ERROR');
          }
          // Show a loading screen while the data is beeing fetched:
          return const CircularProgressIndicator();
        });
  }

This is all working fine, the problem only begins when I need to update this data. For example, when the user deletes a creditCard, I want to delete the card from the List and to re-render the page with the new version of the List, but I don't know a good way of doing that.

In order to get updated data/ refresh the FutureBuilder, you need to reassign the future variable.

For your case, when ever you like to update,

_futureCreditCards = controller.getCreditCards();
setState((){});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM