Jona
Jona

Reputation: 315

Run Future again from Parent

So I have a HomePage with a Scaffold and an IconButton refresh. When I press the button I want to run the Future from MyCustomListView again in case there is new data.

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(
              icon: Icon(Icons.refresh),
              onPressed: () {

              }),
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
        child: 
            MyCustomListView()
      ),
    );
  }

This is my widget MyCustomListView():

class MyCustomListView extends StatelessWidget {
  Future<List<MyData>> getMyData() async {
    try {
      final response = await http.get(
          Uri.encodeFull(
              'myurl'),);

      if (response.statusCode == 200) {
        return MyDataEntity.fromJson(json.decode(response.body)).myData;
      }
    } catch (e) {
      throw Exception(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<MyData>>(
      future: getMyData(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return SliverToBoxAdapter(
            child: Center(
              child: Spinner(),
            ),
          );
        } else {
          final _myData = snapshot.data;
          return SliverList(
            delegate: SliverChildBuilderDelegate(
              (BuildContext context, int index) {

              },
              childCount: _myData == null ? 0 : _myData.length,
            ),
          );
        }
      },
    );
  }
}

How can I run the Future again from its parent in HomePage? Do I need a GlobalKey, another function and have to convert the widget to StateFul?

Upvotes: 0

Views: 34

Answers (2)

Mammad
Mammad

Reputation: 119

In this scenario you can use normal Buider convert to Statefull widget and load your data in initState .

@override
void initState() {
    super.initState();
    // load data here
    // call steState
}

Don't forget to run setState in initState

Upvotes: 0

Josteve Adekanbi
Josteve Adekanbi

Reputation: 12673

A workaround is to make your page a StatefulWidget then call setState when you press the button.

It will call the build method again hence, re-loading the new data

    IconButton(
      onPressed: (){
        setState((){

        });
      },
    )

I hope this helps you.

Upvotes: 1

Related Questions