按下Flutter的浮动动作按钮的简单对话框

时间:2019-12-15 08:01:34

标签: flutter mobile flutter-layout flutter-animation flutter-test

我是一名初学者,在这里弄清楚我的代码出了什么问题时,我需要一些帮助

我试图使浮动操作按钮显示一个简单的对话框(并添加内容),但是我不确定为什么当我按下FAB时无法将简单的对话框显示出来。我知道它必须在无状态小部件,但我似乎无法在无状态/有状态小部件段中插入FAB。是否有解决方法?

任何帮助将不胜感激。

 void main() {
    runApp(MaterialApp(
     debugShowCheckedModeBanner: false,
     home: Scaffold(
       bottomNavigationBar: BottomAppBar(
         child: Text(
           "test bottom",
          style: TextStyle(
            color: Color(0xffFFFFFF),
             fontSize: 10,
            ),
           textAlign: TextAlign.center,
          ),
          color: Colors.blueGrey[600],
          ),
         backgroundColor: Colors.lightBlueAccent[50],
             appBar: AppBar(
          title: Text('test'),
           backgroundColor: Colors.blueGrey[600],
        ),
        body: SoundTest(),
       floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.blue,
         child: Icon(Icons.priority_high),
         onPressed: () {
           print('hello');
        },
       ),
     ),
      ));
     }

 class SoundTest extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
     return Column(
  crossAxisAlignment: CrossAxisAlignment.stretch,

  children: <Widget>[
    Expanded(
      child: FlatButton(
        child: Image.asset('images/softsound.png'),
        onPressed: () {
          final player = AudioCache();
          player.play('clicksoft.wav');
          showDialog(context: context,
          );
        },
      ),
    ),
    Expanded(
      child: FlatButton(
          child: Image.asset('images/loudsound.png'),
          onPressed: () {
            final player = AudioCache();
            player.play('clickloud.wav');
          }),
         )
        ],
      );
     }
  }

2 个答案:

答案 0 :(得分:0)

方法1

StatefulWidget

完整示例,查找完整代码here

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

  final String title;

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

class _MyHomePageState extends State<Login> {


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(),
      floatingActionButton: FloatingActionButton(onPressed: (){_showDialog();}),
    );
  }

  void _showDialog() {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Alert Dialog title"),
          content: new Text("Alert Dialog body"),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("Close"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}

方法2

声明一个_scaffoldKey

  var _scaffoldKey = new GlobalKey<ScaffoldState>();

_scaffoldkey分配给您的Scaffold

  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: Container(),
      floatingActionButton: FloatingActionButton(onPressed: (){_showDialog();}),
    );
  }

然后将_scaffoldKey.currentContext传递到对话框context:_scaffoldKey.currentContext,

  void _showDialog() {
    // flutter defined function
    showDialog(
      context: _scaffoldKey.currentContext,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Alert Dialog title"),
          content: new Text("Alert Dialog body"),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("Close"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

输出:

enter image description here

答案 1 :(得分:0)

基本上Ravinder Kumar是对的。因为您似乎不熟悉,所以基于创建新项目时生成的示例代码,我制作了一个易于理解的示例。因此,我的建议是生成一个新项目并粘贴我的代码,以便了解如何修改应用程序。我建议像我一样使用StatefulWidget

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      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> {
  void _showDialog() {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: new Text("Alert Dialog title"),
          content: new Text("Alert Dialog body"),
          actions: <Widget>[
            new FlatButton(
              child: new Text("Close"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Push the FAB to display a dialog.',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _showDialog,
        tooltip: 'Show Dialog',
        child: Icon(Icons.add),
      ),
    );
  }
}

编辑: 我拿了你的代码,并在工厂中插入了一个对话框...

import 'package:audioplayers/audio_cache.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(debugShowCheckedModeBanner: false, home: HomePage()));
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      bottomNavigationBar: BottomAppBar(
        child: Text(
          "test bottom",
          style: TextStyle(
            color: Color(0xffFFFFFF),
            fontSize: 10,
          ),
          textAlign: TextAlign.center,
        ),
        color: Colors.blueGrey[600],
      ),
      backgroundColor: Colors.lightBlueAccent[50],
      appBar: AppBar(
        title: Text('test'),
        backgroundColor: Colors.blueGrey[600],
      ),
      body: SoundTest(),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.blue,
        child: Icon(Icons.priority_high),
        onPressed: () {
          showDialog(
            context: context,
            builder: (BuildContext context) {
              // return object of type Dialog
              return AlertDialog(
                title: new Text("Alert Dialog title"),
                content: new Text("Alert Dialog body"),
                actions: <Widget>[
                  // usually buttons at the bottom of the dialog
                  new FlatButton(
                    child: new Text("Close"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        },
      ),
    );
  }
}

class SoundTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
          child: FlatButton(
            child: Image.asset('images/softsound.png'),
            onPressed: () {
              final player = AudioCache();
              player.play('clicksoft.wav');
              //I do not know what this is supposed to do...
              //If you want to show the dialog here, simply copy/paste from above...
              /*showDialog(context: context,
          );*/
            },
          ),
        ),
        Expanded(
          child: FlatButton(
              child: Image.asset('images/loudsound.png'),
              onPressed: () {
                final player = AudioCache();
                player.play('clickloud.wav');
              }),
        )
      ],
    );
  }
}