flutter 处理模型生成按钮的onPress

qyswt5oh  于 2023-03-13  发布在  Flutter
关注(0)|答案(2)|浏览(215)

我有一个模型为了回答这个问题我把它简化了

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,并将更新后的模型发送回主类

ddrv8njm

ddrv8njm1#

您需要Panel在模型更改时提供回调函数,然后您就可以更改应用中使用的模型。请注意添加到Panel的“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(),
        ));
  }
}
wmomyfyw

wmomyfyw2#

您可以执行以下操作:
1.您可以创建一个Global Variable,它包含一个dictionary/hasmap,而不是遵循模型。

/* 
  This is the primary util for maintaining 
  all the Global values/variables
*/
library globals;

//This is your variable
Map<String, dynamic> mydata = {'a':0, 'b':0, 'c':0};

现在,您可以在任何文件的任何位置访问全局值,只需导入globals.dart文件(如import '{path}/globals.dart'
1.现在在您的Panel中,我们可以访问它,并按照您的意愿进行项目的增量

import '{path}/globals.dart' as globals

class Panel extends StatelessWidget {
  List<Widget> _buildContent() {
      List<Widget> l = [];
      
      // No list declaration, direct items access
      globals.mydata.forEach((key, value) {
        l.add(
         FlatButton(
           child: Text(key), 
           onPressed: (key) {
               //on pressed you just increment when it is hit for the key elem
               globals.mydata[key] += 1;
           }
        ));
    });
    return l;
  }

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

1.最后一步,现在当你点击按钮,你会得到更新的HasMap,它是全局可访问的,所以你可以调用Panel(),不需要参数,当你想检查更新的值时,只需要打印它

import '{path}/globals.dart' as globals

Panel()

// This will give out the updated data if the button is hit else {'a': 0, 'b': 0, 'c': 0}
print(globals.mydata)

这是我能为你考虑的最干净的方式。

相关问题