zoukankan      html  css  js  c++  java
  • flutter 简单的StatefullWeiget 获取内部事件的值

    直接上代码,利用回调方法获取内部事件的值

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';
    
    typedef void OnRaidoChange(String val);      // 声明一个方法
    
    class RadioSelect extends StatefulWidget {
      final List<String> items;
      final OnRaidoChange onValueChangedCallBack;  // 用于回调,主要就是使用这个方法获取内部的值
    
      RadioSelect(
          {GlobalKey<_RadioSelectState> key,     // GlobalKey
          @required this.items,
          this.onValueChangedCallBack})
          : super(key: key);
    
      GlobalKey<_RadioSelectState> getKey() {
        return this.key;
      }
    
      @override
      _RadioSelectState createState() {
        return new _RadioSelectState();
      }
    }
    
    class _RadioSelectState extends State<RadioSelect> {
      List<Widget> itemWidget = new List();      // 通过Wiget列表方式给Children赋值
      String value;
    
      @override
      void initState() {
        if (widget.items == null) {
          throw new Exception(
              '<RadioSelect> attribute ``items`` must not be null.');
        }
        for (int i = 0; i < widget.items.length; i++) {
          itemWidget.add(
            Container(
              child: GestureDetector(
                child: Row(
                  children: <Widget>[
                    Container(
                            child: Icon(Icons.check_circle),
                          ),
                    Container(
                      child: Text(widget.items[i]),
                    )
                  ],
                ),
                onTap: () {
                  setState(() {
                    this.value = widget.items[i];    // 点击赋值  
                  });
                  if (widget.onValueChangedCallBack != null) {
                    widget.onValueChangedCallBack(widget.items[i]);  // 把值传给方法,谁调谁知道
                  }
                },
              ),
            ),
          );
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Wrap(
            children: itemWidget,
          ),
        );
      }
    }

    使用:

    var items = ['1', '2'];
    return Row(
      children: <Widget>[
        RadioSelect(
          items: items,
          onValueChangedCallBack: (val) {
            _radioValue = val;
          },
        ),
        FlatButton(
          child: Text('点我'),
          onPressed: () {
            print(_radioValue);
          },
        ),
      ],
    );
  • 相关阅读:
    155. 最小栈
    160. 相交链表
    PAT 1057 Stack
    PAT 1026 Table Tennis
    PAT 1017 Queueing at Bank
    PAT 1014 Waiting in Line
    PAT 1029 Median
    PAT 1016 Phone Bills
    PAT 1010 Radix
    PAT 1122 Hamiltonian Cycle
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/12100268.html
Copyright © 2011-2022 走看看