gpt4 book ai didi

flutter - 通过模型生成的按钮处理onPress

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

为了这个问题,我有一个简化的模型

MyModel(a:0, b:0, c:0) //a b c are integers
现在,我需要从该模型生成按钮,因此我创建了一个新类,该类将该模型作为参数并生成按钮
class Panel extends StatelessWidget {
final MyModel model;

const Panel({this.model});

List<Widget> _buildContent() {
final list = [
{'a': model.a},
{'b': model.b},
{'c': model.c}
];
List<Widget> l = [];
list.forEach((element) {
l.add(FlatButton(child: Text(element.keys.first), onPressed: () {}));
});
return l;
}

@override
Widget build(BuildContext context) {
return Container(
height: 70,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _buildContent(),
));
}
}
在我的主类,我只是这样称呼它
Panel(model: myModel);
我正在尝试找到最灵活的方式来处理这些按钮的按下,每个按钮应该在每次按下时将其元素更新为+1,并将更新后的模型发送回主类

最佳答案

您需要面板在模型更改时提供回调。然后,您可以更改应用程序中使用的模型。请注意,添加到面板的“onChange”回调在应用程序中调用setState来实际更改模型。
例:

import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
runApp(MyApp());
}

class Model {
final int a;
final int b;
final int c;

const Model({this.a, this.b, this.c});
}

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
Model model = Model(a: 1, b: 2, c: 3);

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(title: Text('Current Model: a:${model.a}, b:${model.b}, c: ${model.c}')),
body: Center(
child: Panel(
model: model,
onChange: (changedModel) => setState(() => model = changedModel)),
),
),
);
}
}

class PanelButton {
final String text;
final Model Function() onClick;

const PanelButton(this.text, this.onClick);
}

class Panel extends StatelessWidget {
final Model model;
final void Function(Model) onChange;

const Panel({@required this.model, this.onChange});

List<Widget> _buildContent() {
final list = [
PanelButton('a', () => Model(a: model.a + 1, b: model.b, c: model.c)),
PanelButton('b', () => Model(a: model.a, b: model.b + 1, c: model.c)),
PanelButton('c', () => Model(a: model.a, b: model.b, c: model.c + 1)),
];

return list
.map((x) => FlatButton(
child: Text(x.text), onPressed: () => _raiseOnChange(x.onClick())))
.toList();
}

void _raiseOnChange(Model model) {
if (onChange != null) {
onChange(model);
}
}

@override
Widget build(BuildContext context) {
return Container(
height: 70,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _buildContent(),
));
}
}

关于flutter - 通过模型生成的按钮处理onPress,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62691527/

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