聆听另一个文件中的按钮单击

时间:2020-09-07 22:50:04

标签: flutter dart

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

现在,我已将其导入到主.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,
      ),
    );
  }
}


1 个答案:

答案 0 :(得分:0)

您可以在下面复制粘贴运行完整代码
步骤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:您可以使用convert ButtonCheckState显示数据并获取attribue isActive

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

工作演示

enter image description here

完整代码

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()}'),
          ],
        ),
      ),
    );
  }
}