skip to Main Content

I create a parent page contains a list about custom widgets, the list is variable so I can add or decrease the number of these custom widgets immediately.

The custom widgets are contained by

  List<FoodContainer> _foods = [];

in parent page.

The custom widget looks like:

class FoodContainer extends StatefulWidget {
  const FoodContainer({
    Key? key,
  }) : super(key: key);

  @override
  _FoodContainerState createState() => _FoodContainerState();
}

class _FoodContainerState extends State<FoodContainer> {

  var _result;
  
  @override
  Widget build(BuildContext context) {
    return Container(
      child :TextField(
        onSubmitted: (String s){
          setState(() {
            _result = Func(s);
          });
        },
      ),
    );
  }
}

Now I want to get the value of _result in every child widget,how can I get them?

I tried to do like this:

class FoodContainer extends StatefulWidget {
  const FoodContainer({
    Key? key,
    required this.foodTextControl,
  }) : super(key: key);
  final TextEditingController foodTextControl;

The widget.foodTextControl.text can be read in parent page, but the Func(s) is a web request, I don’t want to request twice.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for Aswanath C K,I created a simple custom controller to get the child widget info.

    class TestController extends ValueNotifier<String>{
      TestController({ String? text }) : super(text == null ? "None" : text);
    
      TestController.fromValue(String? value)
      :assert(
          value == null,'Now:${value}'
        ),
        super(value ?? "None");
    
      String get text => value;
    
      set text(String newText) {
        value = newText;
      }
    
      @override
      set value(String newValue) {
        super.value = newValue;
      }
    }
    

    When the _result changes,make

    widget.testController.text = _result;
    

    Now it's finished.


  2. If you want the _result of all the children (FoodContainers) to the parent (ListView.builder).Then you can use

    final ValueChanged<String> onChanged;
    

    and when the onSubmitted is called you can use this like:

    widget.onChanged(_result);
    

    And on the parent(Listview) you can get the access by:

    FoodContainer(
    onChanged: (val){
       print(val);
       }
    

    I hope this will resolve your issue.

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