gpt4 book ai didi

android-studio - 如何单击单击后具有其自己的StatelessWidget类的开关?

转载 作者:行者123 更新时间:2023-12-03 04:20:05 24 4
gpt4 key购买 nike

我试图使两个开关在单击时在打开和关闭之间切换。我为交换机的设计创建了StatelessWidget类。但是,当我使用它并在我的用户界面类中调用该类时,开关不会更改状态。如何更新代码以进行更改?

import 'package:flutter/material.dart';

class NotificationItem extends StatelessWidget {
NotificationItem(
{@required this.title,
@required this.pushStatus,
@required this.emailStatus});

String title;
bool pushStatus;
bool emailStatus;

@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(
child: Padding(
padding: EdgeInsets.all(20),
child: Text(
title,
style: TextStyle(
fontFamily: kFontFamilyNormal,
fontSize: 17,
color: AppColor.text,
fontWeight: FontWeight.w500),
),
),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Switch(
value: emailStatus,
onChanged: (value) {
emailStatus = value;
print(emailStatus);
},
activeTrackColor: AppColor.primaryColorDark,
activeColor: AppColor.white,
),
Switch(
value: pushStatus,
onChanged: (value) {
pushStatus = value;
print(pushStatus);
},
activeTrackColor: AppColor.primaryColorDark,
activeColor: AppColor.white,
),
],
),
),
],
);
}
}
以下代码是我的称呼方式:
NotificationItem(
title: 'New messages',
emailStatus: emailStatus,
pushStatus: pushStatus,
)

最佳答案

由于您要更改状态,因此它必须是StatefulWidget。像这样:

class NotificationItem extends StatefulWidget {
const NotificationItem({
Key key,
@required this.title,
@required this.pushStatus,
@required this.emailStatus,
});
final String title;
final bool pushStatus;
final bool emailStatus;

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

class _NotificationItemState extends State<NotificationItem> {
String _title;
bool _pushStatus;
bool _emailStatus;

void initState() {
super.initState();
_title = widget.title;
_pushStatus = widget.pushStatus;
_emailStatus = widget.emailStatus;
}

@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
Expanded(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
_title,
),
),
),
Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Switch(
value: _emailStatus,
onChanged: (value) {
setState(() => _emailStatus = value);
print(_emailStatus);
},
),
Switch(
value: _pushStatus,
onChanged: (value) {
setState(() => _pushStatus = value);
print(_pushStatus);
},
),
],
),
),
],
);
}
}

关于android-studio - 如何单击单击后具有其自己的StatelessWidget类的开关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63181566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com