首页 > 解决方案 > 单击按钮时显示小部件(Dart,Flutter)

问题描述

单击按钮时如何显示小部件(例如更多按钮)。

FlatButton(
          onPressed: () {
            //render the new widgets
          },
          
          child: Icon(
            Icons.close,
            color: Colors.white,
          ),
        ));

这是父类 class StopStream extends StatelessWidget

标签: flutterdart

解决方案


  1. 您可以借助变量有条件地显示/隐藏小部件。
  2. 您需要一个 StatefulWidget 来更改小部件的状态,即动态显示/隐藏(小部件)。

请看下面的代码,我使用 abool showWidget来显示或隐藏更多FlatButton的 a Row

import 'package:flutter/material.dart';

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  bool showWidget = false;
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        showWidget
            ? Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  FlatButton(
                    onPressed: () {},
                    child: const Icon(Icons.ac_unit),
                  ),
                  FlatButton(
                    onPressed: () {},
                    child: const Icon(Icons.accessible),
                  ),
                  FlatButton(
                    onPressed: () {},
                    child: const Icon(Icons.backpack),
                  ),
                  FlatButton(
                    onPressed: () {},
                    child: const Icon(Icons.cached),
                  ),
                ],
              )
            : Container(),
        FlatButton(
          onPressed: () {
            setState(() {
              showWidget = !showWidget;
            });
          },
          child: const Icon(
            Icons.close,
            color: Colors.white,
          ),
        ),
      ],
    );
  }
}

推荐阅读