flutter:dialog (十一)

简介: 本文介绍了 Flutter 中常用的弹窗组件和方法,包括 `AlertDialog`、`SimpleDialog`、`showModalBottomSheet` 和 `toast`。每个组件的使用方法和示例代码都进行了详细说明,帮助开发者快速理解和应用这些弹窗功能。例如,`AlertDialog` 用于显示带有标题、内容和按钮的对话框;`SimpleDialog` 用于显示多个选项供用户选择;`showModalBottomSheet` 用于从屏幕底部弹出模态对话框;而 `toast` 则用于显示短暂的消息提示。文中还提供了如何处理点击事件、取消弹窗等常见操作的代码示例。

前言

在现代应用中,弹窗是与用户互动的重要形式,能够有效地传达信息、提示操作或收集反馈。Flutter提供了一系列强大的弹窗组件,开发者可以根据需求选择合适的组件来提升用户体验。本文将聚焦于Flutter中常用的弹窗组件,包括AlertDialog、SimpleDialog、showModalBottomSheet和Toast。每个组件将附带详细的使用方法和示例代码,确保开发者能够快速理解和应用这些功能。

AlertDialog

属性

barrierDismissible: false, //  点击 背景 不消失  默认 为 true

定义一个 按钮

AlertDialog

ElevatedButton(
                //   按钮 点击 方法  不 带 括号
                onPressed: _alertDialog,
                child: Text("dialog test"),
              )

方法 如下

//  异步 改为 同步  得到  返回 值
  void _alertDialog() async {
    var res = await showDialog(
        builder: (context) {
          return AlertDialog(
            title: Text("title"),
            content: Text("content"),
            actions: [
              TextButton(
                onPressed: () {
                  // pop   为  返回值  可以 用 res  接收
                  Navigator.of(context).pop("cancel");
                },
                child: Text("cancel"),
              ),
              TextButton(
                  onPressed: () {
                    //            返回
                    Navigator.of(context).pop("confirm");
                  },
                  child: Text("confirm")),
            ],
          );
        }, context: this.context);
    print(res);
  }
shape: ShapeBorder.lerp(
      RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
      CircleBorder(),
      1,
    ),
    icon: Icon(Icons.add),


SimpleDialog

void _simpleDialog() async {
 var res2=  await showDialog(
      barrierDismissible: false, //  点击 背景 不消失  默认 为 true
        context: context,
        builder: (context) {
          return SimpleDialog(
            title: Text("switch language"),
            children: [
              SimpleDialogOption(
                onPressed: () {
              //  设置 pop 返回的值 
                  Navigator.of(context).pop("chinese");
                },
                child: Text("chinese"),
              ),
              SimpleDialogOption(
                onPressed: () {
                  Navigator.of(context).pop("english");
                },
                child: Text("english"),
              ),
              SimpleDialogOption(
                onPressed: () {
                  Navigator.of(context).pop("japan");
                },
                child: Text("japan"),
              ),
            ],
          );
        });


showModelBottomSheet


底部 出现  弹窗

void _modelBottomSheet(){
      showModalBottomSheet(context: context, builder: (context){
        return  SizedBox(
          height: 300,
          child: Column(
            children: [
              ListTile(title: Text("share"),),
              ListTile(title: Text("collect"),),
              ListTile(title: Text("cancel"),),
            ],
          ),
        );
      });
  }


toast

在dependcies  下面  添加

fluttertoast: ^8.0.9
在 需要用 到 的 页面 进行 
import 'package:fluttertoast/fluttertoast.dart';

使用

void _toast(){
     Fluttertoast.showToast(msg: "this is toast",
     toastLength: Toast.LENGTH_LONG,
       backgroundColor: Colors.red,
       textColor: Colors.white,
       fontSize: 16.0,
       gravity: ToastGravity.CENTER,
     );
  }

弹框

简单使用

simpleDialog

import 'package:flutter/material.dart';
class test extends StatefulWidget {
  const test({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _test();
}
class _test extends State<test> {
  @override
  Widget build(BuildContext context) {
    void showSimpleFn() async {
      bool? isSelect = await showDialog<bool>(
          context: context,
          builder: (context) {
            return SimpleDialog(
              title: Text('title'),
              children: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                  child: Text('select one'),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                  child: Text('select one'),
                ),
              ],
            );
          });
      print("close $isSelect");
    }
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            showSimpleFn();
          },
          child: Text('click me'),
        ),
      ),
    );
  }
}
void main() {
  runApp(MaterialApp(
    home: test(),
  ));
}

底部弹窗

import 'package:flutter/material.dart';
class test extends StatefulWidget {
  const test({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() => _test();
}
class _test extends State<test> {
  void showBottomSheetFn(BuildContext context) {
    showBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return buildContainer(context);
        });
  }
  Container buildContainer(BuildContext context) {
    return Container(
      //  背景  颜色
      color: Colors.white,
      height: 180,
      width: double.infinity,
      child: Column(
        children: <Widget>[
          Container(
            alignment: Alignment.center,
            height: 44,
            child: const Text("title"),
          ),
          const Expanded(child: Text("content")),
          //     分割上下
          //给一点线 分割
          Container(
            height: 1,
            color: Colors.grey[200],
          ),
          SizedBox(
            height: 64,
            child: Row(
              children: [
                Expanded(
                    child: TextButton(
                  child: const Text("cancel"),
                  onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                )),
                Container(
                  // 给一个 宽
                  width: 1,
                  color: Colors.grey[200],
                ),
                Expanded(
                    child: TextButton(
                        child: const Text("confirm"),
                           onPressed: () {
                    Navigator.of(context).pop(false);
                  },
                )),
              ],
            ),
          )
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Builder(
          builder: (BuildContext context) {
            return ElevatedButton(
              onPressed: () {
                showBottomSheetFn(context);
              },
              child: const Text('click me'),
            );
          },
        ),
      ),
    );
  }
}
void main() {
  runApp(MaterialApp(
    home: test(),
  ));
}

注意点

定义一个方法

void showBottomSheetFn(BuildContext context) {
    showBottomSheet(context: context, builder: (BuildContext context){
      return buildContainer(context);
    });

点击取消

Navigator.of(context).pop(false);

点击背景 弹窗取消

barrierDismissible:rue

使用builder 封装   来获得 context

return Scaffold(
      body:Center(
      child: Builder(
        builder: (BuildContext context){
        return  ElevatedButton(onPressed: () { showBottomSheetFn(context); }, child: const Text('click me'),);
        },
      ),
      ),
    );

showModalBottomSheet

void showDemo(BuildContext context) async{
    showModalBottomSheet(context: context,
    backgroundColor: Colors.grey,
        // 模糊背景颜色
        barrierColor: Colors.grey,
      // 点击背景消失
      isDismissible: true,
      // 下滑消失
      enableDrag: true,
      builder: (BuildContext context){
      return buildContainer(context);
      }
    );
  }
import 'package:flutter/material.dart';
class test extends StatefulWidget{
  const test({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() =>_test();
}
class _test extends State<test> {
  void showDemo(BuildContext context) async{
    showModalBottomSheet(context: context,
    backgroundColor: Colors.grey,
        // 模糊背景颜色
        barrierColor: Colors.grey,
      // 点击背景消失
      isDismissible: true,
      // 下滑消失
      enableDrag: true,
      builder: (BuildContext context){
      return buildContainer(context);
      }
    );
  }
  Container buildContainer(BuildContext context){
    return Container(
      //  背景  颜色
      color: Colors.white,
      height: 180,
      width: double.infinity,
      child: Column(
        children:<Widget> [
          Container(alignment: Alignment.center,
            height: 44,
            child: const Text(
                "title"
            ),
          ),
          const Expanded(child: Text("content")),
          //给一点线 分割
          Container(height: 1,
            color: Colors.grey[200],),
          SizedBox(
            height: 64,
            child: Row(
              children: [
                Expanded(child: TextButton(child: const Text("cancel"),onPressed: (){
                  Navigator.of(context).pop(false);
                },)),
                Container(
                  width: 1,
                  color: Colors.grey[200],
                ),Expanded(child: TextButton(child: const Text("confirm"),onPressed: (){Navigator.of(context).pop(false);},)),
              ],
            ),
          )
        ],
      ),
    );
  }
  @override
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Builder(
          builder: (BuildContext context){
            return ElevatedButton(onPressed:(){ showDemo(context);}, child: Text('click me'));
          },
        ),
      ),
    );
  }
}
void  main(){
  runApp(MaterialApp(
    home:test(),
  ));
}
import 'package:flutter/material.dart';
class test extends StatefulWidget{
  const test({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() =>_test();
}
class _test extends State<test> {
  void showDemo(BuildContext context) async{
    showModalBottomSheet(context: context,
    backgroundColor: Colors.grey,
        // 模糊背景颜色
        barrierColor: Colors.grey,
      // 点击背景消失
      isDismissible: true,
      // 下滑消失
      enableDrag: true,
      builder: (BuildContext context){
      return buildContainer(context);
      }
    );
  }
  Container buildContainer(BuildContext context){
    return Container(
      //  背景  颜色
      color: Colors.white,
      height: 180,
      width: double.infinity,
      child: Column(
        children:<Widget> [
          Container(alignment: Alignment.center,
            height: 44,
            child: const Text(
                "title"
            ),
          ),
          const Expanded(child: Text("content")),
          //给一点线 分割
          Container(height: 1,
            color: Colors.grey[200],),
          SizedBox(
            height: 64,
            child: Row(
              children: [
                Expanded(child: TextButton(child: const Text("cancel"),onPressed: (){
                  Navigator.of(context).pop(false);
                },)),
                Container(
                  width: 1,
                  color: Colors.grey[200],
                ),Expanded(child: TextButton(child: const Text("confirm"),onPressed: (){Navigator.of(context).pop(false);},)),
              ],
            ),
          )
        ],
      ),
    );
  }
  @override
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Builder(
          builder: (BuildContext context){
            return ElevatedButton(onPressed:(){ showDemo(context);}, child: Text('click me'));
          },
        ),
      ),
    );
  }
}
void  main(){
  runApp(MaterialApp(
    home:test(),
  ));
}


页面 显示

import 'package:flutter/material.dart';
class test extends StatefulWidget {
  late final Function(int value) callBack;
  test({required this.callBack});
  @override
  State<StatefulWidget> createState() {
    return _test();
  }
}
class _test extends State<test> {
  int _groupValue=0;
  @override
  Widget build(BuildContext context) {
      return Scaffold(
        body: Center(
          child: TextButton(onPressed:
            //  方法
            showDialogFn
          ,child: Text("click me"),)
        ),
      );
  }
  Widget hello(){
    return Scaffold(
        body: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            RadioListTile(
                value: 0,
                title: Text('test A'),
                groupValue: _groupValue,
                onChanged: (value){
                  setState(() {
                    _groupValue=value as int;
                  });
                  widget.callBack(_groupValue);
                }
            ),
            RadioListTile(
                value: 1,
                title: Text('test B'),
                groupValue: _groupValue,
                onChanged: (value){
                  setState(() {
                    _groupValue=value as int;
                  });
                  widget.callBack(_groupValue);
                }
            ),
          ],
        ),
    );
  }
  void showDialogFn()async{
 await showDialog<bool>(
        context: context,
        builder: (context){
          return AlertDialog(
              title: Text("this is title"),
              //   将显示的内容单独封装
              // content:
              content: hello(),
              //   底部按钮
              actions:<Widget>[
                TextButton(onPressed: (){
                  Navigator.of(context).pop(false);
                }, child: Text('Cancel')
                ),
                TextButton(onPressed: (){
                  Navigator.of(context).pop(false);
                }, child:Text('Ok') )
              ]
          );
        }
    );
  }
}
void main() {
  runApp(MaterialApp(
    home: test(callBack: (int value) {}),
  ));
}

第二个

import 'package:flutter/material.dart';
class test extends StatefulWidget{
  const test({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() =>_test();
}
class _test extends State<test> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
  mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            ElevatedButton(onPressed: (){
              NavigatorUtils.openPageByFade(
                context,
                CustomDialogWidget(
                  callBack:(int value){}
                ),
                opaque:false,
              ),
            }, child: Text('show dialog'))
          ],
        ),
      ),
    );
  }
}
void  main(){
  runApp(MaterialApp(
    home:test(),
  ));
}
import 'package:flutter/material.dart';
class test extends StatefulWidget{
  const test({Key? key}) : super(key: key);
  @override
  State<StatefulWidget> createState() =>_test();
}
class _test extends State<test> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
  mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            ElevatedButton(onPressed: (){
              NavigatorUtils.openPageByFade(
                context,
                CustomDialogWidget(
                  callBack:(int value){}
                ),
                opaque:false,
              ),
            }, child: Text('show dialog'))
          ],
        ),
      ),
    );
  }
}
void  main(){
  runApp(MaterialApp(
    home:test(),
  ));
}









相关文章
Flutter自定义Dialog
Flutter自定义Dialog
176 0
Flutter自定义Dialog
【交互 widget】Flutter Dialog
【交互 widget】Flutter Dialog
295 0
【交互 widget】Flutter Dialog
|
Web App开发 Android开发 iOS开发
|
网络架构
Flutter 124: 日常问题小结 (三) 自定义 Dialog 二三事
0 基础学习 Flutter,第一百二十四步:继续整理日常遇到的小问题!
470 0
Flutter 124: 日常问题小结 (三) 自定义 Dialog 二三事
|
Dart iOS开发 容器
|
容器
Flutter 60: 图解基本 Dialog 对话框小结
0 基础学习 Flutter,第六十步:学习一下 Flutter 基础对话框!
2762 0
|
C++ C语言
Flutter 24: 图解自定义 Dialog 对话框
0 基础学习 Flutter,第二十四步:自定义对话框了解下~
4782 0
|
2月前
|
Android开发 iOS开发 容器
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
鸿蒙harmonyos next flutter混合开发之开发FFI plugin
|
8天前
|
传感器 前端开发 Android开发
在 Flutter 开发中,插件开发与集成至关重要,它能扩展应用功能,满足复杂业务需求
在 Flutter 开发中,插件开发与集成至关重要,它能扩展应用功能,满足复杂业务需求。本文深入探讨了插件开发的基本概念、流程、集成方法、常见类型及开发实例,如相机插件的开发步骤,同时强调了版本兼容性、性能优化等注意事项,并展望了插件开发的未来趋势。
22 2
|
2月前
|
开发者
鸿蒙Flutter实战:07-混合开发
鸿蒙Flutter混合开发支持两种模式:1) 基于har包,便于主项目开发者无需关心Flutter细节,但不支持热重载;2) 基于源码依赖,利于代码维护与热重载,需配置Flutter环境。项目结构包括AppScope、flutter_module等目录,适用于不同开发需求。
80 3