Flutter步进器控件插件gsstepper的使用

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

Flutter步进器控件插件gsstepper的使用

GSStepper 是一个 Flutter 包,提供了自定义的步进器小部件。它允许你在应用程序中创建一个逐步过程,引导用户通过多个阶段或任务。该小部件可以根据你的需求选择滚动或固定步进器。

你可以通过设置各种属性(如颜色、大小、图标和标签)来自定义步进器以适应应用的设计。此外,你可以轻松地跟踪用户的进度,通过更新每个步骤的状态和进度值。

安装

要使用此包,在 pubspec.yaml 文件中添加 gsstepper 作为依赖项。

flutter pub add gsstepper

pubspec.yaml 文件中添加以下内容:

dependencies:
  gsstepper: ^0.0.4

使用

将包导入到 Dart 代码中:

import 'package:gsstepper/gsstepper.dart';

创建一个 GSStepper 小部件,并传递一个 GSStep 小部件列表给它:

stepper = GSStepper.scrollable(
  currentIndex: currentStep,
  style: StepperStyle(),
  steps: widget.stepperItemList,
  stepperData: GSStepperData(),
  stepWidth: 100,
  onComplete: () {
    // 当所有步骤完成时调用
  },
  onNextStep: (index) {
    currentStep = index;
    setState(() {});
  },
),

或者,如果你想使用固定的 GSStepper,可以这样做:

stepper = GSStepper.fixed(
  currentIndex: currentStep,
  style: StepperStyle(),
  steps: widget.stepperItemList,
  stepperData: GSStepperData(),
  stepWidth: 100,
  onComplete: () {
    // 当所有步骤完成时调用
  },
  onNextStep: (index) {
    currentStep = index;
    setState(() {});
  },
),

示例代码

以下是一个完整的示例代码,展示了如何使用 GSStepper 插件。

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

void main() {
  runApp(const MainWidget());
}

class MainWidget extends StatelessWidget {
  const MainWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      themeMode: ThemeMode.light,
      locale: const Locale('en', 'US'),
      supportedLocales: const [
        Locale('en', 'US'),
        Locale('fa', 'IR'),
      ],
      theme: ThemeData(
        brightness: Brightness.light,
        primaryColor: Colors.blue,
        textTheme: null,
        colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.blue)
            .copyWith(secondary: Colors.blueAccent, brightness: Brightness.light),
      ),
      darkTheme: ThemeData(
        brightness: Brightness.dark,
        colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.blue)
            .copyWith(secondary: Colors.blueAccent, brightness: Brightness.dark),
      ),
      home: const MainScreen(),
    );
  }
}

class MainScreen extends StatelessWidget {
  const MainScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ElevatedButton(
                child: const Text('Fixed Stepper'),
                onPressed: () {
                  Navigator.pushAndRemoveUntil<dynamic>(
                    context,
                    MaterialPageRoute<dynamic>(builder: (BuildContext context) => FixedStepperSampleScreen()),
                    (route) => true, // 如果你想禁用返回功能,请设为 false
                  );
                },
              ),
              ElevatedButton(
                child: const Text('Scrollable Stepper'),
                onPressed: () {
                  Navigator.pushAndRemoveUntil<dynamic>(
                    context,
                    MaterialPageRoute<dynamic>(builder: (BuildContext context) => ScrollableStepperSampleScreen()),
                    (route) => true, // 如果你想禁用返回功能,请设为 false
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// 固定步进器示例
class FixedStepperSampleScreen extends StatefulWidget {
  FixedStepperSampleScreen({Key? key}) : super(key: key);

  List<GSStepModel> stepperItemList = [
    GSStepModel(
      globalKey: GlobalKey(),
      icon: const Icon(
        Icons.store,
        color: Colors.white,
        size: 12,
      ),
      status: GSStepStatusEnum.inActive,
      progress: 0,
      stepName: 'User Information Step',
      stepNumber: 'Step One',
    ),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Information',
        stepNumber: 'Step two'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Shop Information',
        stepNumber: 'Step tree'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
  ];

  @override
  State<FixedStepperSampleScreen> createState() => _FixedStepperSampleScreenState();
}

class _FixedStepperSampleScreenState extends State<FixedStepperSampleScreen> {
  int currentStep = 0;
  late GSStepper stepper;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Expanded(
              child: stepper = GSStepper.fixed(
                currentIndex: currentStep,
                style: StepperStyle(),
                steps: widget.stepperItemList,
                stepperData: GSStepperData(),
                onComplete: () {
                  // 当所有步骤完成时调用
                },
                onNextStep: (index) {
                  currentStep = index;
                  setState(() {});
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      child: const Text('Previous'),
                      onPressed: () {
                        if (currentStep > 0) {
                          stepper.goToStep(
                            currentStatus: widget.stepperItemList[stepper.currentIndex].status!,
                            nextIndex: stepper.currentIndex - 1,
                            currentStepProgress: widget.stepperItemList[stepper.currentIndex].progress,
                            nextStepProgress: widget.stepperItemList[stepper.currentIndex - 1].progress,
                          );
                        }
                      },
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: ElevatedButton(
                      child: const Text('Next'),
                      onPressed: () {
                        if (currentStep < widget.stepperItemList.length) {
                          stepper.goToStep(
                              currentStatus: GSStepStatusEnum.success,
                              nextIndex: stepper.currentIndex + 1,
                              currentStepProgress: 100,
                              nextStepProgress: 30);
                        }
                      },
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

// 滚动步进器示例
class ScrollableStepperSampleScreen extends StatefulWidget {
  ScrollableStepperSampleScreen({Key? key}) : super(key: key);

  List<GSStepModel> stepperItemList = [
    GSStepModel(
      globalKey: GlobalKey(),
      icon: const Icon(
        Icons.store,
        color: Colors.white,
        size: 12,
      ),
      status: GSStepStatusEnum.inActive,
      progress: 0,
      stepName: 'User Information Step',
      stepNumber: 'Step One',
    ),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Information',
        stepNumber: 'Step two'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Shop Information',
        stepNumber: 'Step tree'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
    GSStepModel(
        globalKey: GlobalKey(),
        icon: const Icon(
          Icons.store,
          color: Colors.white,
          size: 12,
        ),
        status: GSStepStatusEnum.inActive,
        progress: 0,
        stepName: 'Photos',
        stepNumber: 'Step four'),
  ];

  @override
  State<ScrollableStepperSampleScreen> createState() => _ScrollableStepperSampleScreenState();
}

class _ScrollableStepperSampleScreenState extends State<ScrollableStepperSampleScreen> {
  int currentStep = 0;
  late GSStepper stepper;

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Expanded(
              child: stepper = GSStepper.scrollable(
                currentIndex: currentStep,
                style: StepperStyle(),
                steps: widget.stepperItemList,
                stepperData: GSStepperData(),
                stepWidth: 100,
                onComplete: () {
                  // 当所有步骤完成时调用
                },
                onNextStep: (index) {
                  currentStep = index;
                  setState(() {});
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                children: [
                  Expanded(
                    child: ElevatedButton(
                      child: const Text('Previous'),
                      onPressed: () {
                        if (currentStep > 0) {
                          stepper.goToStep(
                            currentStatus: widget.stepperItemList[stepper.currentIndex].status!,
                            nextIndex: stepper.currentIndex - 1,
                            currentStepProgress: widget.stepperItemList[stepper.currentIndex].progress,
                            nextStepProgress: widget.stepperItemList[stepper.currentIndex - 1].progress,
                          );
                        }
                      },
                    ),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: ElevatedButton(
                      child: const Text('Next'),
                      onPressed: () {
                        if (currentStep < widget.stepperItemList.length) {
                          stepper.goToStep(
                              currentStatus: GSStepStatusEnum.success,
                              nextIndex: stepper.currentIndex + 1,
                              currentStepProgress: 100,
                              nextStepProgress: 30);
                        }
                      },
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

自定义

要创建一个 GSStepModel 的实例,你可以传入以下参数:

  • globalKey(必需):这是一个 GlobalKey 用于标识步骤。
  • icon(可选):一个表示步骤图标的 Icon 小部件。
  • status(可选):一个 GSStepStatusEnum 枚举值,表示步骤的状态,默认值为 inActive
  • progress(可选):一个表示步骤进度的整数。
  • stepName(可选):一个表示步骤名称或描述的字符串。
  • stepNumber(可选):一个表示步骤编号的字符串。

以下是如何创建一个 GSStepModel 实例的例子:

List<GSStepModel> stepperItemList = [
  GSStepModel(
    globalKey: GlobalKey(),
    icon: const Icon(Icons.store,
      color: Colors.white,
      size: 12,
    ),
    status: GSStepStatusEnum.inActive,
    progress: 0,
    stepName: 'User Information Step',
    stepNumber: 'Step 1',
  ),
  // 添加更多的 GSStepModel 对象
];

更多关于Flutter步进器控件插件gsstepper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter步进器控件插件gsstepper的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter项目中使用gs_stepper插件来实现步进器控件的示例代码。gs_stepper是一个流行的Flutter插件,用于创建复杂的步进器界面。

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

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

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

接下来,在你的Flutter应用中,你可以按照以下步骤使用gs_stepper控件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Stepper Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyStepperPage(),
    );
  }
}

class MyStepperPage extends StatefulWidget {
  @override
  _MyStepperPageState createState() => _MyStepperPageState();
}

class _MyStepperPageState extends State<MyStepperPage> {
  final _formKey = GlobalKey<FormState>();
  int _currentStep = 0;
  String _name = '';
  String _email = '';

  List<Step> getSteps() {
    return [
      Step(
        title: Text('Step 1: Enter your name'),
        content: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Form(
            key: _formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                TextFormField(
                  decoration: InputDecoration(labelText: 'Name'),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please enter your name';
                    }
                    return null;
                  },
                  onSaved: (value) {
                    _name = value;
                  },
                ),
              ],
            ),
          ),
        ),
        isActive: _currentStep >= 0,
        state: _formKey.currentState!.validate() ? StepState.complete : StepState.editing,
      ),
      Step(
        title: Text('Step 2: Enter your email'),
        content: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              TextFormField(
                decoration: InputDecoration(labelText: 'Email'),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  if (value == null || value.isEmpty || !value.contains('@')) {
                    return 'Please enter a valid email';
                  }
                  return null;
                },
                onSaved: (value) {
                  _email = value;
                },
              ),
            ],
          ),
        ),
        isActive: _currentStep >= 1,
        state: _formKey.currentState!.validate() ? StepState.complete : StepState.editing,
      ),
      Step(
        title: Text('Step 3: Review'),
        content: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: <Widget>[
              Text('Name: $_name'),
              Text('Email: $_email'),
            ],
          ),
        ),
        isActive: _currentStep >= 2,
        state: StepState.complete,
      ),
    ];
  }

  void _submit() {
    if (_formKey.currentState!.validate()) {
      _formKey.currentState!.save();
      // 在这里处理表单提交,例如发送数据到服务器
      print('Name: $_name, Email: $_email');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Stepper Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Expanded(
              child: Stepper(
                steps: getSteps(),
                currentStep: _currentStep,
                onStepTapped: (int step) {
                  setState(() {
                    _currentStep = step;
                  });
                },
                onStepContinue: () {
                  setState(() {
                    if (_currentStep < getSteps().length - 1) {
                      _currentStep = _currentStep + 1;
                    } else {
                      // 提交表单
                      _submit();
                    }
                  });
                },
                onStepCancel: () {
                  setState(() {
                    if (_currentStep > 0) {
                      _currentStep = _currentStep - 1;
                    }
                  });
                },
              ),
            ),
            ElevatedButton(
              onPressed: () {
                if (_currentStep == getSteps().length - 1) {
                  // 如果已经在最后一步,则提交表单
                  _submit();
                } else {
                  // 否则,继续到下一步
                  setState(() {
                    if (_currentStep < getSteps().length - 1) {
                      _currentStep++;
                    }
                  });
                }
              },
              child: Text('Next'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个包含三个步骤的步进器:

  1. 第一步:要求用户输入姓名。
  2. 第二步:要求用户输入电子邮件。
  3. 第三步:显示用户输入的信息供用户审核。

每个步骤都包含了一个TextFormField用于数据输入,并且使用FormGlobalKey进行表单验证。Stepper控件管理步骤的导航,包括继续、取消和跳转到特定步骤。

请根据需要调整这个示例以适应你的具体需求。

回到顶部