Search code examples
flutterflutter-layoutflutter-provider

How to wrap a List of Widgets without changing the layout when unwrapped and spread in a Row?


Currently, the following structure gives me the intended layout:

Consumer<State>(
  builder(context, state, child) => Row(
    children: [
      Widget1(...), // fixed width
      ...List.generate(state.length, (index) => Expanded(child: Widget2(index, state))),
    ]
  )
)

Widget1 does not need to be hooked up to state, and so I don't want it to be rerendered when it changes. It would be great if List.generate could be hooked to a Consumer, but builder needs to return a single Widget, not a list of Widgets.

I've tried using the Wrap widget around the list, and hooking that to a Consumer. This accomplishes my goal of not rerendering Widget1, but it changes the layout - the Widget2's don't expand to fill the remaining space any longer.


Solution

  • Here's an example:

    Row(
      children: [
        Widget1(...), // fixed width
          Consumer<State>(
           builder: (context, state, child) {
              return Expanded(
                       child: Row(
                         children: List.generate(
                           state.length,
                           (index) {
                             return Expanded(
                               child: Widget2(index, state),
                             );
                           },
                         ),
                       ),
                     );
                   },
                 ),
               ],
             ),