0

I Have a BottomNavigationBar, and there are multiple pages within it. One of my pages is a Statefulwidget, and within this widget, there is a Future builder. However, I would rather not rebuild my FutureBuilder even after switching tabs.

class CurrenPlanDetail extends StatefulWidget {
  static const routeName = 'current-plan-detail';
  @override
  State<CurrenPlanDetail> createState() => _CurrenPlanDetailState();
}

class _CurrenPlanDetailState extends State<CurrenPlanDetail> {

  Future<int>? _myFuture;

 

  @override
  void didChangeDependencies() {
    if (_isInit) {
      Provider.of<Plans>(context).getServerPlan(_errorDialog);
    }
    _isInit = false;
    super.didChangeDependencies();
  }

  @override
  void initState() {
    _myFuture = returnData();
    super.initState();
  }

  Future<int> returnData() async {
    return await Provider.of<Users>(context, listen: false).subRemainDays();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        //elevation: 0,
        title: Text('title'),
        //backgroundColor: Colors.transparent,
      ),
      //backgroundColor: kFrostyWhite,
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CurrentPlanBox(),
            FutureBuilder(
                future: _myfuture,
                builder: (context, snapshot) {
                  if (snapshot.connectionState == ConnectionState.waiting) {
                    return Text('loading....');
                  }
                  return Text(snapshot.data.toString());
                }),
            Container(
              margin: EdgeInsets.only(top: 10.h),
              child: PlanSlider(),
            ),
          ],
        ),
      ),
    );
  }
}

I attempted to declare my future as a variable within the initSatate method, but it doesn't work Every time I switch tabs, my future gets reloaded.

Behnam
  • 329
  • 5
  • 15
  • (For statefullWidget) If you need to load for a single time, use `initState` by creating a separate future method or else `StreamBuilder`. – Md. Yeasin Sheikh Apr 13 '22 at 18:31
  • I declare my future inside initstate, but it doesn't work – Behnam Apr 13 '22 at 18:37
  • You can remove `FutureBuilder` from build method, then create a future method, you can check [this approach](https://stackoverflow.com/a/71860309/10157127) – Md. Yeasin Sheikh Apr 13 '22 at 18:39
  • Does this answer your question? [Flutter Switching to Tab Reloads Widgets and runs FutureBuilder](https://stackoverflow.com/questions/51224420/flutter-switching-to-tab-reloads-widgets-and-runs-futurebuilder) – Mashood .H Sep 02 '22 at 00:14
  • Look at this [answer](https://stackoverflow.com/questions/51224420/flutter-switching-to-tab-reloads-widgets-and-runs-futurebuilder/73576517#73576517) I've also mentioned a Statement Solution With Getx. – Mashood .H Sep 02 '22 at 17:44

0 Answers0