skip to Main Content

A bit of a Flutter newbie, I hope you can help with this question.

I have two widgets on the main screen of my app. the top widget is a Facebook banner ad widget, the bottom part of the screen is then taken up with a list that is populated from an web API call.

When I use the toolbar to refresh the data from the API, I am using SetState to rebuild the list etc.

However, the top widget, with the Facebook ad is also being rebuilt each time, which is not what I want.

I have seen lots of talk about Bloc Patterns etc. If sounds like a bit of overkill for what I want to do, is there an easier way to just update the list without updating the banner ad widget?

Thanks

3

Answers


  1. you should add a key property to your widget, it allows you to keep a specific widget from rebuilding when changing state.

    Login or Signup to reply.
  2. I can think of two solutions:

    1. move the list to a separate StatefulWidget. If setState() is now called in this widget, only the included widget will be rebuilt.
    2. something in the direction:
    class _MyWidgetState extends State<MyWidget> {
      Widget _facebookBanner;
      
      @override
      void initState() {
        _facebookBanner = ...;
        super.initState();
      }
      
      @override
      Widget build(BuildContext context) {
        return Column(children: <Widget>[
          _facebookBanner,
          ListView(...),
        ]);
      }
    }
    
    Login or Signup to reply.
  3. You can define the Facebook banner as const, it won’t be rebuilt when declared like that

    This is an example of how to use const keyword

    child: const Text('This is just an example of a const widget');
    

    Const constructors are a great optimization for stuff that you know that won’t change.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search