Returning data from a Stateful Widget in Flutter

后端 未结 2 1681
借酒劲吻你
借酒劲吻你 2021-01-19 04:21

I have previously posted about this problem I am still facing Which is to return data from a Stateful widget back to a Stateless Widget

The Widget I am using is Dat

2条回答
  •  爱一瞬间的悲伤
    2021-01-19 04:30

    For more time saving solution for returning value from another widget and using it, here's an example for Flutter Dropdown:

    import 'package:flutter/material.dart';
    import 'package:paxi_ride/constant.dart';
    
    class BuildDropdown extends StatefulWidget {
      final ValueChanged onChanged;
      String defaultValue, selectedValue, dropdownHint;
      List itemsList;
    
      BuildDropdown(
          {Key key,
          this.itemsList,
          this.defaultValue,
          this.dropdownHint,
          this.onChanged})
          : super(key: key);
    
      @override
      _BuildDropdownState createState() => _BuildDropdownState();
    }
    
    class _BuildDropdownState extends State {
      String _value;
    
      @override
      Widget build(BuildContext context) {
        return Container(
          // height: 40,
          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 0),
          margin: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          color: Colors.white,
          child: DropdownButton(
            items: widget.itemsList.map(
              (String value) {
                return new DropdownMenuItem(
                  value: value,
                  child: new Text(value),
                );
              },
            ).toList(),
            value: _value == null ? widget.defaultValue : _value,
            isExpanded: true,
            onChanged: (String value) {
              setState(() {
                _value = value;
              });
              widget.onChanged(value);
            },
            hint: Text(widget.dropdownHint),
            style: TextStyle(
              fontSize: 14,
              color: brownColorApp,
            ),
            iconEnabledColor: brownColorApp,
            iconSize: 14,
            underline: Container(),
          ),
        );
      }
    }
    

    Call this widget from another widget where you want to get selected value like this:

    String selectedValue; //class field
    
    BuildDropdown(
              itemsList: ['Option 1','Option 2'],
              defaultValue: 'Option 1',
              dropdownHint: 'Select Required Option',
              onChanged: (value) {
                selectedValue = value;
              },
            ),
    

    Use this value wherever needed, it will be changed as dropdown selection is changed.

提交回复
热议问题