Flutter浮动操作按钮插件form_floating_action_button的使用

发布于 1周前 作者 gougou168 来自 Flutter

Flutter浮动操作按钮插件 form_floating_action_button 的使用

简介

form_floating_action_button 是一个为 Flutter 应用中的浮动操作按钮(FAB)添加基本表单功能的插件。它可以帮助你在表单提交时进行验证和处理。

Demo

安装

pubspec.yaml 文件中添加依赖:

dependencies:
  ...
  form_floating_action_button: any

使用示例

导入包

首先,导入 form_floating_action_button.dart 包:

import 'package:form_floating_action_button/form_floating_action_button.dart';

在表单中使用

以下是一个完整的示例,展示了如何在表单中使用 FormFloatingActionButton

import 'package:flutter/material.dart';
import 'package:form_floating_action_button/form_floating_action_button.dart';

class FormValidatePage extends StatefulWidget {
  [@override](/user/override)
  _FormValidatePageState createState() => _FormValidatePageState();
}

class _FormValidatePageState extends State<FormValidatePage> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final FormFloatingActionButtonController _controller = FormFloatingActionButtonController();
  bool _loading = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form Validate'),
      ),
      body: Form(
        key: _formKey,
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: ListView(
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Email',
                ),
                validator: (value) {
                  if (value?.isEmpty ?? true) {
                    return 'Email is required';
                  } else if (!value!.contains('@') || !value.contains('.')) {
                    return 'Email is not valid';
                  }
                  return null;
                },
              ),
              SizedBox(height: 20),
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Password',
                ),
                obscureText: true,
                validator: (value) {
                  if (value?.isEmpty ?? true) {
                    return 'Password is required';
                  }
                  return null;
                },
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FormFloatingActionButton(
        controller: _controller,
        loading: _loading,
        onSubmit: () async {
          if (_formKey.currentState?.validate() ?? false) {
            setState(() => _loading = true);
            await Future.delayed(Duration(seconds: 3));
            setState(() => _loading = false);
            ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Form Submitted')));
          }
        },
      ),
    );
  }
}

自定义验证逻辑

你也可以自定义验证逻辑,例如:

import 'package:flutter/material.dart';
import 'package:form_floating_action_button/form_floating_action_button.dart';

class OnValidatePage extends StatefulWidget {
  [@override](/user/override)
  _OnValidatePageState createState() => _OnValidatePageState();
}

class _OnValidatePageState extends State<OnValidatePage> {
  bool _validateSuccess = true;
  bool _loading = false;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('On Validate'),
      ),
      body: ListView(
        children: <Widget>[
          ListTile(
            onTap: () {
              setState(() => _validateSuccess = !_validateSuccess);
            },
            title: Text('Validation Successful'),
            trailing: IgnorePointer(
              child: Switch(
                value: _validateSuccess,
                onChanged: (_) {},
              ),
            ),
          )
        ],
      ),
      floatingActionButton: FormFloatingActionButton(
        loading: _loading,
        onSubmit: () async {
          setState(() => _loading = true);
          await Future.delayed(Duration(seconds: 3));
          setState(() => _loading = false);
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Form Submitted')));
        },
        onValidate: () {
          return Future.value(_validateSuccess);
        },
      ),
    );
  }
}

完整的示例项目结构

以下是完整的示例项目结构,包含主页面和两个子页面:

import 'package:flutter/material.dart';

import 'src/page_form_validate.dart';
import 'src/page_on_validate.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({
    super.key,
  });

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Form FAB Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Form FAB Example'),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) {
                      return const PageOnValidate();
                    },
                  ),
                );
              },
              child: const Text('On Validate Example'),
            ),
            const SizedBox(height: 16.0),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) {
                      return const PageFormValidate();
                    },
                  ),
                );
              },
              child: const Text('Form Validate Example'),
            ),
          ],
        ),
      ),
    );
  }
}

更多关于Flutter浮动操作按钮插件form_floating_action_button的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter浮动操作按钮插件form_floating_action_button的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter项目中使用form_floating_action_button插件的示例代码。这个插件通常用于在表单下方添加一个浮动操作按钮(FAB),以便用户快速提交表单内容。

首先,确保你已经在pubspec.yaml文件中添加了form_floating_action_button依赖项:

dependencies:
  flutter:
    sdk: flutter
  form_floating_action_button: ^x.y.z  # 替换为最新版本号

然后,运行flutter pub get来安装依赖项。

接下来,在你的Flutter项目中,你可以按照以下方式使用FormFloatingActionButton

import 'package:flutter/material.dart';
import 'package:form_floating_action_button/form_floating_action_button.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Form Floating Action Button Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16.0),
          child: FormFloatingActionButtonExample(),
        ),
        floatingActionButton: FormFloatingActionButton(
          onPressed: () {
            // 这里是提交表单的逻辑
            print('Form submitted!');
          },
          child: Icon(Icons.send),
          backgroundColor: Colors.blue,
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        bottomNavigationBar: BottomAppBar(
          shape: CircularNotchedRectangle(),
          notchMargin: 4.0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              IconButton(icon: Icon(Icons.menu), onPressed: () {}, tooltip: 'Navigate back'),
              IconButton(icon: Icon(Icons.search), onPressed: () {}, tooltip: 'Search'),
            ],
          ),
        ),
      ),
    );
  }
}

class FormFloatingActionButtonExample extends StatefulWidget {
  @override
  _FormFloatingActionButtonExampleState createState() => _FormFloatingActionButtonExampleState();
}

class _FormFloatingActionButtonExampleState extends State<FormFloatingActionButtonExample> {
  final _formKey = GlobalKey<FormState>();
  String _name = '';
  String _email = '';

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          TextFormField(
            decoration: InputDecoration(labelText: 'Name'),
            validator: (value) {
              if (value.isEmpty) {
                return 'Please enter your name';
              }
              return null;
            },
            onSaved: (value) {
              _name = value;
            },
          ),
          TextFormField(
            decoration: InputDecoration(labelText: 'Email'),
            keyboardType: TextInputType.emailAddress,
            validator: (value) {
              if (value.isEmpty || !value.contains('@')) {
                return 'Please enter a valid email';
              }
              return null;
            },
            onSaved: (value) {
              _email = value;
            },
          ),
          SizedBox(height: 20),
          // 这里可以添加更多的表单字段
        ],
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个表单和两个文本字段(用于输入姓名和电子邮件)。当用户点击浮动操作按钮时,会打印出“Form submitted!”的消息。在实际应用中,你可以将onPressed回调中的逻辑替换为提交表单数据的代码。

注意:FormFloatingActionButton的位置和样式(如背景颜色)可以根据需要进行调整。在这个例子中,我们将其位置设置为FloatingActionButtonLocation.centerDocked,并在底部导航栏中添加了额外的图标按钮。

希望这个示例对你有所帮助!如果你有任何其他问题,请随时询问。

回到顶部