'Flutter: How to force didchangedependencies or InitStateto to be executed in a StatefulWidget Class

I've the following code, the code working fine. It retrieves News from DB and presents it in the ListView. The News have two types (1 and 2).

class NewsFragment extends StatefulWidget {
  NewsFragment({Key? key, required this.eltype}) : super(key: key);
  final int eltype;

  @override State<StatefulWidget> createState() {
    return new NewsFragmentState();
  }
}

class NewsFragmentState extends State<NewsFragment> {
  late Future <List<news_item>> futureData;

  ( ... )
  
  Future <List<news_item>> fetchNews({eltype: 0, lu: 0}) async {
    ...
  }
  
  @override
  initState() {
    super.initState();

    void getNewsfromDB({eltype: 0}) async {
      futureData = fetchNews(eltype: eltype);
    }
    getNewsfromDB(eltype: widget.eltype);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Center(
          child: FutureBuilder <List<news_item>> (
            future: futureData,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<news_item> data = snapshot.data!;
                BDS_Utilities.BDS_log('Element Type:${widget.eltype} #${data.length}', 'build');
                return
                  Scaffold(
                    body: (data.length > 0)
                        ? ListView.separated(
                          (...)

There is a parameter to pass to the NewsFragment class, the class is called by a Drawer ...

  _getDrawerItemWidget(int pos) {
    switch (pos) {
      case 1:
        return new NewsFragment(eltype: 0);
      case 2:
        return new NewsFragment(eltype: 1);
      case 3:
        return new MapFragment();
      ...
      other cases ...

If new NewsFragment(eltype: 0) is called and then new NewsFragment(eltype: 1), or vice versa, nothing changes, the initState() is not called so the content is not refreshed. If new NewsFragment(eltype: 0) is called then new MapFragment(), then new NewsFragment(eltype: 1) the initState() is invoked and the content is refreshed since it is fetched from the DB via FetchNews function.

How can I refresh the content after several continuous NewsFragment calls with different parameters? How can I tell to NewsFragment to call initState() or didChangeDependencies()? Or only if eltype is different from the actual one.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source