0

I have a function to set the values to the state.

void Function() setSize({double? min, double? max}) {
  final currentState = controller?._controllerState;
  final newState = currentState?.copyWith(
    min: min ?? minSize,
    max: max ?? maxSize,
  );

  controller?._attach(newState ?? setupDefaultState());

  return () => controller?._detach();
}

And a useEffect for updating the state once receiving new values

useEffect(() => setSize(min: minSize, max: maxSize), [minSize, maxSize]);

And the min-max value is getting from a LayoutBuilder

return LayoutBuilder(
  builder: (context, constraints) {
    minSize = constraints.minHeight;
    maxSize = constraints.maxHeight;
    .....
    }

However, the above useEffect only called once right after the screen is opened, and never called again even after the minSize and maxSize have changed in the LayoutBuilder widget. What should I change to make the useEffect works here? Thank you in advance

hrtlkr29
  • 383
  • 1
  • 7
  • 21

1 Answers1

0

The LayoutBuilder needs to wrap a HookBuilder.

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

void main() {
  runApp(
    const MyApp(),
  );
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: LayoutBuilder(
                builder: (context, constraints) =>
                    HookBuilder(builder: (context) {
                      final minSize = constraints.minWidth;
                      final maxSize = constraints.maxWidth;
                      useEffect(() {
                        print("min: $minSize max: $maxSize");
                        return null;
                      }, [minSize, maxSize]);

                      return SizedBox(
                          height: 200,
                          width: maxSize,
                          child: const Placeholder());
                    }))));
  }
}
ValiumdiƤt
  • 163
  • 11