Flutter样式化Toast提示插件flutter_styled_toast的使用

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

Flutter样式化Toast提示插件flutter_styled_toast的使用

flutter_styled_toast

这是一个Flutter包,可以高度自定义Toast。通过一系列动画美化Toast,使Toast更加美观。

OverallAnimations

Null Safety

dependencies:
  flutter_styled_toast: ^2.2.1

Getting Started

添加依赖

dependencies:
  flutter_styled_toast: ^1.5.2+3

导入库

import 'package:flutter_styled_toast/flutter_styled_toast.dart';

基本用法

简单使用,无需全局配置

showToast("hello styled toast", context: context);

自定义Toast内容组件,无需全局配置

showToastWidget(Text('hello styled toast'), context: context);

交互式Toast,设置isIgnoring为false

showToastWidget(
   Container(
       padding: EdgeInsets.symmetric(horizontal: 18.0),
       margin: EdgeInsets.symmetric(horizontal: 50.0),
       decoration: ShapeDecoration(
           shape: RoundedRectangleBorder(
               borderRadius: BorderRadius.circular(5.0),
           ),
           color: Colors.green[600],
       ),
       child: Row(
           children: [
               Text(
                   'Jump to new page',
                   style: TextStyle(
                       color: Colors.white,
                   ),
               ),
               IconButton(
                   onPressed: () {
                       ToastManager().dismissAll(showAnim: true);
                       Navigator.push(context,
                           MaterialPageRoute(builder: (context) {
                           return SecondPage();
                       }));
                   },
                   icon: Icon(
                       Icons.add_circle_outline_outlined,
                       color: Colors.white,
                   ),
               ),
           ],
           mainAxisAlignment: MainAxisAlignment.spaceBetween,
       ),
   ),
   context: context,
   isIgnoring: false,
   duration: Duration.zero,
);

设置动画

showToast('This is normal toast with animation',
   context: context,
   animation: StyledToastAnimation.scale,
);

设置正向和反向动画

showToast('This is normal toast with animation',
   context: context,
   animation: StyledToastAnimation.scale,
   reverseAnimation: StyledToastAnimation.fade,
   position: StyledToastPosition.center,
   animDuration: Duration(seconds: 1),
   duration: Duration(seconds: 4),
   curve: Curves.elasticOut,
   reverseCurve: Curves.linear,
);

自定义动画和反向动画

AnimationController mController;
AnimationController mReverseController;

@override
void initState() {
  super.initState();
  mController =
      AnimationController(vsync: this, duration: Duration(milliseconds: 200));
  mReverseController =
      AnimationController(vsync: this, duration: Duration(milliseconds: 200));
}

showToast('This is normal toast with custom animation',
   context: context,
   position: StyledToastPosition.bottom,
   animDuration: Duration(seconds: 1),
   duration: Duration(seconds: 4),
   animationBuilder: (
       BuildContext context,
       AnimationController controller,
       Duration duration,
       Widget child,
   ) {
      return SlideTransition(
          position: getAnimation<Offset>(
          Offset(0.0, 3.0), Offset(0, 0), controller,
          curve: Curves.bounceInOut),
          child: child,
      );
   },
   reverseAnimBuilder: (
      BuildContext context,
      AnimationController controller,
      Duration duration,
      Widget child,
   ) {
      return SlideTransition(
          position: getAnimation<Offset>(
          Offset(0.0, 0.0), Offset(-3.0, 0), controller,
          curve: Curves.bounceInOut),
          child: child,
      );
   },
);

自定义动画、反向动画和自定义动画控制器

showToast('This is normal toast with custom animation and controller',
   context: context,
   position: StyledToastPosition.bottom,
   animDuration: Duration(seconds: 1),
   duration: Duration(seconds: 4),
   onInitState:(Duration toastDuration, Duration animDuration) async {
      try {
         await mController.forward().orCancel;
         Future.delayed(toastDuration - animDuration, () async {
            await mReverseController.forward().orCancel;
            mController.reset();
            mReverseController.reset();
         });
      } on TickerCanceled {}
   },
   animationBuilder: (
       BuildContext context,
       AnimationController controller,
       Duration duration,
       Widget child,
   ) {
      return SlideTransition(
          position: getAnimation<Offset>(
          Offset(0.0, 3.0), Offset(0, 0), controller,
          curve: Curves.bounceInOut),
          child: child,
      );
   },
   reverseAnimBuilder: (
      BuildContext context,
      AnimationController controller,
      Duration duration,
      Widget child,
   ) {
      return SlideTransition(
          position: getAnimation<Offset>(
          Offset(0.0, 0.0), Offset(-3.0, 0), controller,
          curve: Curves.bounceInOut),
          child: child,
      );
   },
);

全局配置

简单全局配置,包裹你的App

StyledToast(
  locale: const Locale('en', 'US'),
  child: MaterialApp(
    title: appTitle,
    showPerformanceOverlay: showPerformance,
    home: LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return MyHomePage(
          title: appTitle,
          onSetting: onSettingCallback,
        );
      },
    ),
  ),
);

高度可定制的全局配置

StyledToast(
  locale: const Locale('en', 'US'),  
  textStyle: TextStyle(fontSize: 16.0, color: Colors.white), 
  backgroundColor: Color(0x99000000),  
  borderRadius: BorderRadius.circular(5.0), 
  textPadding: EdgeInsets.symmetric(horizontal: 17.0, vertical: 10.0),
  toastPositions: StyledToastPosition.bottom, 
  toastAnimation: StyledToastAnimation.fade,  
  reverseAnimation: StyledToastAnimation.fade, 
  curve: Curves.fastOutSlowIn,  
  reverseCurve: Curves.fastLinearToSlowEaseIn, 
  duration: Duration(seconds: 4), 
  animDuration: Duration(seconds: 1), 
  dismissOtherOnShow: true,  
  movingOnWindowChange: true, 
  fullWidth: false, 
  isHideKeyboard: false, 
  isIgnoring: true, 
  animationBuilder: (BuildContext context,AnimationController controller,Duration duration,Widget child,){  
     return SlideTransition(
        position: getAnimation<Offset>(Offset(0.0, 3.0),Offset(0,0), controller,curve: Curves.bounceInOut),
        child: child,
     );
  },
  reverseAnimBuilder: (BuildContext context,AnimationController controller,Duration duration,Widget child,){ 
     return SlideTransition(
        position: getAnimation<Offset>(Offset(0.0, 0.0),Offset(-3.0,0), controller,curve: Curves.bounceInOut),
        child: child,
     );
  },
  child: MaterialApp(
    title: appTitle,
    showPerformanceOverlay: showPerformance,
    home: LayoutBuilder(
      builder: (BuildContext context, BoxConstraints constraints) {
        return MyHomePage(
          title: appTitle,
          onSetting: onSettingCallback,
        );
      },
    ),
  ),
);

使用全局配置后,一行代码显示Toast

showToast("hello styled toast");

使用全局配置后,自定义Toast内容组件

showToastWidget(Text('hello styled toast'));

示例代码

以下是完整的示例代码,展示了如何在项目中使用flutter_styled_toast

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';

void main() {
  debugPaintSizeEnabled = false;
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  bool showPerformance = false;

  onSettingCallback() {
    setState(() {
      showPerformance = !showPerformance;
    });
  }

  @override
  Widget build(BuildContext context) {
    final appTitle = 'Styled Toast Example';
    return StyledToast(
      textStyle: TextStyle(fontSize: 16.0, color: Colors.white),
      backgroundColor: Color(0x99000000),
      borderRadius: BorderRadius.circular(5.0),
      textPadding: EdgeInsets.symmetric(horizontal: 17.0, vertical: 10.0),
      toastAnimation: StyledToastAnimation.size,
      reverseAnimation: StyledToastAnimation.size,
      startOffset: Offset(0.0, -1.0),
      reverseEndOffset: Offset(0.0, -1.0),
      duration: Duration(seconds: 4),
      animDuration: Duration(seconds: 1),
      alignment: Alignment.center,
      toastPositions: StyledToastPosition.center,
      curve: Curves.fastOutSlowIn,
      reverseCurve: Curves.fastOutSlowIn,
      dismissOtherOnShow: true,
      locale: const Locale('en', 'US'),
      fullWidth: false,
      isHideKeyboard: false,
      isIgnoring: true,
      child: MaterialApp(
        title: appTitle,
        showPerformanceOverlay: showPerformance,
        home: LayoutBuilder(
          builder: (BuildContext context, BoxConstraints constraints) {
            return MyHomePage(
              title: appTitle,
              onSetting: onSettingCallback,
            );
          },
        ),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String? title;
  final VoidCallback? onSetting;

  MyHomePage({Key? key, this.title, this.onSetting}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage>
    with TickerProviderStateMixin<MyHomePage> {
  String dismissRemind = '';
  TextEditingController controller = TextEditingController();
  late AnimationController mController;
  late AnimationController mReverseController;

  @override
  void initState() {
    super.initState();
    mController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
    mReverseController =
        AnimationController(vsync: this, duration: Duration(milliseconds: 200));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title ?? ''),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.settings),
            onPressed: () {
              widget.onSetting?.call();
            },
          )
        ],
      ),
      body: Center(
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 20.0),
          children: <Widget>[
            // 各种Toast展示按钮...
          ],
        ),
      ),
    );
  }
}

class SecondPage extends StatefulWidget {
  final String? title;

  SecondPage({Key? key, this.title}) : super(key: key);

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

class _SecondPageState extends State<SecondPage> {
  Color getColor(Set<MaterialState> states) {
    const Set<MaterialState> interactiveStates = <MaterialState>{
      MaterialState.pressed,
      MaterialState.hovered,
      MaterialState.focused,
    };
    if (states.any(interactiveStates.contains)) {
      return Colors.blue;
    }
    return Colors.red;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title ?? 'Second Page'),
      ),
      body: Center(
        child: ListView(
          padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 20.0),
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: 10.0),
              padding: EdgeInsets.only(left: 15.0),
              height: 35.0,
              alignment: Alignment.centerLeft,
              child: Text('second page Toast'),
              color: const Color(0xFFDDDDDD),
            ),
            Container(
              height: 50.0,
              margin: EdgeInsets.only(bottom: 20.0),
              child: ElevatedButton(
                onPressed: () {
                  showToast(
                    'This is normal toast',
                  );
                },
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.resolveWith(getColor)),
                child: Text(
                  'normal toast',
                  style: TextStyle(fontSize: 15.0, color: Colors.white),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

这个示例展示了如何在Flutter应用中使用flutter_styled_toast插件来创建各种样式的Toast提示。你可以根据需要调整参数和样式,以适应你的应用需求。


更多关于Flutter样式化Toast提示插件flutter_styled_toast的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter样式化Toast提示插件flutter_styled_toast的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter中使用flutter_styled_toast插件来样式化Toast提示的示例代码。首先,确保你已经在pubspec.yaml文件中添加了依赖项:

dependencies:
  flutter:
    sdk: flutter
  flutter_styled_toast: ^2.0.0  # 请使用最新版本

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

接下来,在你的Flutter项目中,你可以按照以下步骤使用flutter_styled_toast

  1. 导入插件

    在你的Dart文件中导入flutter_styled_toast

    import 'package:flutter_styled_toast/flutter_styled_toast.dart';
    
  2. 初始化插件(可选,但推荐):

    main.dart中,你可以选择在应用启动时初始化插件。尽管这不是必需的,但某些配置(如全局样式)可以在此时设置。

    void main() {
      FlutterStyledToast.init(
        context: context, // 注意:这里你需要一个有效的BuildContext
        position: ToastPosition.bottom,
        backgroundColor: Colors.black.withOpacity(0.7),
        textColor: Colors.white,
        duration: ToastDuration.long,
        textStyle: TextStyle(fontWeight: FontWeight.bold),
        animationDuration: 500,
        isDisplayedOnlyOne: true,
        gravity: ToastGravity.center,
        horizontalMargin: 24.0,
        verticalMargin: 24.0,
        radius: 24.0,
      );
      runApp(MyApp());
    }
    

    注意:在main函数中直接使用context可能会遇到问题,因为此时context还未完全初始化。通常,你会在MaterialAppbuilder属性中初始化插件,或者在一个Widget的initState方法中初始化(如果你需要在某个特定的Widget中使用Toast)。

  3. 显示Toast

    现在,你可以在任何Widget中显示Toast消息了。

    import 'package:flutter/material.dart';
    import 'package:flutter_styled_toast/flutter_styled_toast.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(),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Flutter Styled Toast Demo'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                ElevatedButton(
                  onPressed: () {
                    FlutterStyledToast.showToast(
                      context: context,
                      text: "Hello, Flutter Styled Toast!",
                      backgroundColor: Colors.green,
                      textColor: Colors.white,
                      duration: ToastDuration.short,
                      textStyle: TextStyle(fontSize: 18),
                    );
                  },
                  child: Text('Show Toast'),
                ),
              ],
            ),
          ),
        );
      }
    }
    

在上面的代码中,当用户点击按钮时,会显示一个带有绿色背景和白色文本的Toast消息。

这个示例展示了如何使用flutter_styled_toast插件来显示自定义样式的Toast消息。你可以根据需要调整showToast方法的参数来设置不同的样式。

回到顶部