Home > Software engineering >  Flutter: Layout Builder refreshing Future Builders
Flutter: Layout Builder refreshing Future Builders

Time:07-02

I am trying to achieve responsive layout in a flutter website with using layout builder and have some future builders in the layout, each time i try to resize the browser window the layout builder is rebuilt and thus the future builder also updates, sending the API requests again, and that is the issue. I want to have a responsive layout without futures getting rebuilt, is this possible?

This is the responsive template I am using:


class Responsive extends StatelessWidget {
  final Widget mobile;
  final Widget tablet;
  final Widget desktop;

  const Responsive({
    Key? key,
    required this.mobile,
    required this.tablet,
    required this.desktop,
  }) : super(key: key);

  static bool isMobile(BuildContext context) =>
      MediaQuery.of(context).size.width < 650;

  static bool isTablet(BuildContext context) =>
      MediaQuery.of(context).size.width < 1100 &&
      MediaQuery.of(context).size.width >= 650;

  static bool isDesktop(BuildContext context) =>
      MediaQuery.of(context).size.width >= 1100;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        if (constraints.maxWidth >= 1100) {
          return desktop;
        } else if (constraints.maxWidth >= 650) {
          return tablet;
        } else {
          return mobile;
        }
      },
    );
  }
}

CodePudding user response:

Can you try? :

  • Use StatefullWidget for widget of mobile, table, desktop.
  • Create variable for future on initState() and put it to FutureBuiler on build() function

example:

class _BlogPageState extends State<BlogPage> {

  late Future future;

  @override
  void initState() {
    super.initState();
    future = Future.delayed(...);
  }
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: future,
      builder: builder,
    );
  }
}
  • Related