首页 > 解决方案 > 监听来自另一个文件的按钮点击

问题描述

我创建了一个类似于复选框的按钮,当您单击它时,它会更改以显示您已选择它,反之亦然以取消选择.... on/off .. true/false。

现在我已经将它导入到 main .dart.. 并调用了两次按钮(传递不同的参数以创建不同的文本)以获得两个按钮。如何在main.dart文件中区分第一个按钮和第二个按钮单击以及其中一个是打开还是关闭,并显示输出:

MaterialApp(
      home: Scaffold(
          body: Column(
        children: [
          ButtonCheck('Text1'),
          ButtonCheck('Text2'),
Text('Button1 is '), // on or off
Text('Button2 is '),

        ],
      )),
    );

按钮:接受文本参数,如下所示:--GestureDetector出于设计目的使用和容器,代码被简化--

import 'package:flutter/material.dart';

class ButtonCheck extends StatefulWidget {
  String text;
  ButtonCheck(
    this.text,
  );
  _ButtonCheckState createState() => _ButtonCheckState();
}

class _ButtonCheckState extends State<ButtonCheck> {
  String text;

  void initState() {
    text = widget.text;

    super.initState();
  }

  var _textStyle;

  void ActivateButton() {
    setState(() {
      _textStyle = TextStyle(fontSize: 20, color: Colors.green);
    });
  }

  void DeactivateButton() {
    setState(() {
      _textStyle = TextStyle(fontSize: 18, color: Colors.red);
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() {
        if (_textStyle == TextStyle(fontSize: 18, color: Colors.red)) {
          ActivateButton();
        } else {
          DeactivateButton();
        }
      }),
      child: Text(
        '${text}',
        textAlign: TextAlign.center,
        style: _textStyle,
      ),
    );
  }
}


标签: flutterdart

解决方案


您可以在下面复制粘贴运行完整代码
第 1 步:您可以使用GlobalKey并传递refresh回调

GlobalKey _button1Key = GlobalKey();
...
class ButtonCheck extends StatefulWidget {
  String text;
  VoidCallback callback;
  ButtonCheck({Key key, this.text, this.callback}) : super(key: key);
...
void ActivateButton() {
    setState(() {
      isActive = true;
      _textStyle = TextStyle(fontSize: 20, color: Colors.green);
    });
    if (widget.callback != null) {
      widget.callback();
    }
  }

第2步:你可以通过GlobalKey

ButtonCheck(key: _button1Key, text: 'Text1', callback: refresh),

第 3 步:您可以使用 convertButtonCheckState和 get显示数据attribue isActive

Text('Button1 is ${(_button1Key.currentState as ButtonCheckState)?.isActive?.toString()}'), 

工作演示

在此处输入图像描述

完整代码

import 'package:flutter/material.dart';

class ButtonCheck extends StatefulWidget {
  String text;
  VoidCallback callback;
  ButtonCheck({Key key, this.text, this.callback}) : super(key: key);
  ButtonCheckState createState() => ButtonCheckState();
}

class ButtonCheckState extends State<ButtonCheck> {
  String text;
  bool isActive;

  @override
  void initState() {
    text = widget.text;
    super.initState();
  }

  var _textStyle;

  void ActivateButton() {
    setState(() {
      isActive = true;
      _textStyle = TextStyle(fontSize: 20, color: Colors.green);
    });
    if (widget.callback != null) {
      widget.callback();
    }
  }

  void DeactivateButton() {
    setState(() {
      isActive = false;
      _textStyle = TextStyle(fontSize: 18, color: Colors.red);
    });
    if (widget.callback != null) {
      widget.callback();
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => setState(() {
        if (_textStyle == TextStyle(fontSize: 18, color: Colors.red)) {
          ActivateButton();
        } else {
          DeactivateButton();
        }
      }),
      child: Text(
        '${text}',
        textAlign: TextAlign.center,
        style: _textStyle,
      ),
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  GlobalKey _button1Key = GlobalKey();
  GlobalKey _button2Key = GlobalKey();

  void refresh() {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ButtonCheck(key: _button1Key, text: 'Text1', callback: refresh),
            ButtonCheck(
              key: _button2Key,
              text: 'Text2',
              callback: refresh,
            ),
            Text(
                'Button1 is ${(_button1Key.currentState as ButtonCheckState)?.isActive?.toString()}'), // on or off
            Text(
                'Button2 is ${(_button2Key.currentState as ButtonCheckState)?.isActive?.toString()}'),
          ],
        ),
      ),
    );
  }
}

推荐阅读