StatefulWidget/StatelessWidget 传参及使用

目录

    • StatefulWidget
        • StatefulWidget/基本用法
        • StatefulWidget 接收参数
        • 传入参数到StatefulWidget
        • StatefulWidget 使用接收到的参数
    • StatelessWidget 基本用法
        • StatelessWidget 接收参数
        • 传入参数到StatelessWidget
        • StatelessWidget 使用接收到的参数

StatefulWidget

StatefulWidget/基本用法
class name extends StatefulWidget {
  name({Key key}) : super(key: key);

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

class _nameState extends State<name> {
  @override
  Widget build(BuildContext context) {
    return Container(
       child: child, //具体的内容
    );
  }
}
StatefulWidget 接收参数
class DatePicker extends StatefulWidget {
	//onCancel/onSure是上个页面传过来的值
  DatePicker({Key key, this.onCancel, this.onSure}) : super(key: key);
  final Function onSure;
  final Function onCancel;
  @override
  _DatePickerState createState() =>
      _DatePickerState(onCancel: this.onCancel, onSure: this.onSure);  //传递给_DatePickerState
}
class _DatePickerState extends State<DatePicker> {
  final Function onSure;
  final Function onCancel;
  _DatePickerState({this.onSure, this.onCancel});  //接收DatePicker传过来的值
}
传入参数到StatefulWidget

使用DatePicker
使用用法联动地址

DatePicker(
  onCancel: () {
    Navigator.of(context).pop();
  },
  onSure: (value) async {
    //确认回调
    //处理data或业务逻辑
    setState(() {
      birthday = value;
    });
    Navigator.pop(context);
    // print(value); 
  },
);
StatefulWidget 使用接收到的参数

简单的使用方法

child: GestureDetector(
  onTap: () {
    onCancel();
  },
  child: Text("取消"),
)

StatelessWidget 基本用法

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

  @override
  Widget build(BuildContext context) {
    return Container(
      child: child,//具体内容
    );
  }
}
StatelessWidget 接收参数
class IndexCell extends StatelessWidget {
  final VoidCallback onPressed;
  final String iconName;
  final String title;
  final String content;
  final bool isClick;
  IndexCell({this.title, this.content, this.iconName, this.onPressed, this.isClick});
}
传入参数到StatelessWidget
IndexCell(
  title: '呢称',
  content: username,
  iconName: null,
  isClick: true,
  onPressed: () {
  	//逻辑处理
  },
),
StatelessWidget 使用接收到的参数

简单的使用方法

child: GestureDetector(
  onTap: onPressed,
  child: Text(content),
)

你可能感兴趣的:(app开发,flutter)