Flutter扩展小部件插件some_widget_extensions的使用

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

Flutter扩展小部件插件some_widget_extensions的使用

some_widget_extensions 是一个Dart库,它为Flutter小部件、小部件列表和BuildContext提供了方便的扩展。这些扩展有助于简化小部件组合,并使Flutter代码更加可读和简洁。

特性

  • BuildContext的实用扩展。
  • 对于小部件列表的扩展,用于将它们包裹在常见的Flutter小部件中。
  • 对于单个小部件的扩展,用于将它们包裹在常见的Flutter小部件中。

安装

在你的pubspec.yaml文件中添加some_widget_extensions依赖:

dependencies:
  some_widget_extensions: latest

然后运行pub get来安装包。

使用

导入库:

import 'package:some_widget_extensions/some_widget_extensions.dart';

示例

假设你有以下两个小部件:

final class FirstWidget extends StatelessWidget {
  const FirstWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Text('First');
  }
}

final class SecondWidget extends StatelessWidget {
  const SecondWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Text('Second');
  }
}

使用传统的方法构建一个列(Column):

final traditionalColumnWidget = Column(
  mainAxisSize: MainAxisSize.min,
  children: [
    const Expanded(
      child: Padding(
        padding: EdgeInsets.only(bottom: 8.0),
        child: FirstWidget(),
      ),
    ),
    Container(
      constraints: const BoxConstraints(maxWidth: 145.0),
      child: const SecondWidget(),
    )
  ],
);

使用some_widget_extensions,可以简化为:

final lovelyColumnWidget = [
  const FirstWidget()
      .padding(padding: const EdgeInsets.only(bottom: 8.0))
      .expanded(),
  const SecondWidget()
      .container(constraints: const BoxConstraints(maxWidth: 145.0))
].column(mainAxisSize: MainAxisSize.min);

API

Utility Extensions on BuildContext

ThemeData get theme

从当前BuildContext获取ThemeData

final theme = context.theme;

MediaQueryData get media

从当前BuildContext获取MediaQueryData

final media = context.media;

Extensions on List<Widget>

Column column({...})

将小部件列表包裹在一个Column中。

Column column({
  Key? key,
  MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
  MainAxisSize mainAxisSize = MainAxisSize.max,
  CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
  TextDirection? textDirection,
  VerticalDirection verticalDirection = VerticalDirection.down,
  TextBaseline? textBaseline,
})

Row row({...})

将小部件列表包裹在一个Row中。

Row row({
  Key? key,
  MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
  MainAxisSize mainAxisSize = MainAxisSize.max,
  CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
  TextDirection? textDirection,
  VerticalDirection verticalDirection = VerticalDirection.down,
  TextBaseline? textBaseline,
})

Stack stack({...})

将小部件列表包裹在一个Stack中。

Stack stack({
  Key? key,
  AlignmentGeometry alignment = AlignmentDirectional.topStart,
  TextDirection? textDirection,
  StackFit fit = StackFit.loose,
  Clip clipBehavior = Clip.hardEdge,
})

Flex flex({...})

将小部件列表包裹在一个Flex中。

Flex flex({
  Key? key,
  required Axis direction,
  MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
  MainAxisSize mainAxisSize = MainAxisSize.max,
  CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
  TextDirection? textDirection,
  VerticalDirection verticalDirection = VerticalDirection.down,
  TextBaseline? textBaseline,
  Clip clipBehavior = Clip.none,
})

ListView listView({...})

将小部件列表包裹在一个ListView中。

ListView listView({
  Key? key,
  Axis scrollDirection = Axis.vertical,
  bool reverse = false,
  ScrollController? controller,
  bool? primary,
  ScrollPhysics? physics,
  bool shrinkWrap = false,
  EdgeInsetsGeometry? padding,
  double? itemExtent,
  double Function(int, SliverLayoutDimensions)? itemExtentBuilder,
  Widget? prototypeItem,
  bool addAutomaticKeepAlives = true,
  bool addRepaintBoundaries = true,
  bool addSemanticIndexes = true,
  double? cacheExtent,
  int? semanticChildCount,
  DragStartBehavior dragStartBehavior = DragStartBehavior.start,
  ScrollViewKeyboardDismissBehavior keyboardDismissBehavior =
      ScrollViewKeyboardDismissBehavior.manual,
  String? restorationId,
  Clip clipBehavior = Clip.hardEdge,
})

Extensions on Widget

Card card({...})

将一个小部件包裹在一个Card中。

Card card({
  Key? key,
  Color? color,
  Color? shadowColor,
  Color? surfaceTintColor,
  double? elevation,
  ShapeBorder? shape,
  bool borderOnForeground = true,
  EdgeInsetsGeometry? margin,
  Clip? clipBehavior,
  bool semanticContainer = true,
})

SafeArea safeArea({...})

将一个小部件包裹在一个SafeArea中。

SafeArea safeArea({
  Key? key,
  bool left = true,
  bool top = true,
  bool right = true,
  bool bottom = true,
  EdgeInsets minimum = EdgeInsets.zero,
  bool maintainBottomViewPadding = false,
})

Padding padding({...})

将一个小部件包裹在一个Padding中。

Padding padding({
  Key? key,
  required EdgeInsetsGeometry padding,
})

SizedBox sizedBox({...})

将一个小部件包裹在一个SizedBox中。

SizedBox sizedBox({
  Key? key,
  double? width,
  double? height,
})

Container container({...})

将一个小部件包裹在一个Container中。

Container container({
  Key? key,
  AlignmentGeometry? alignment,
  EdgeInsetsGeometry? padding,
  Color? color,
  Decoration? decoration,
  Decoration? foregroundDecoration,
  double? width,
  double? height,
  BoxConstraints? constraints,
  EdgeInsetsGeometry? margin,
  Matrix4? transform,
  AlignmentGeometry? transformAlignment,
  Clip clipBehavior = Clip.none,
})

Expanded expanded({...})

将一个小部件包裹在一个Expanded中。

Expanded expanded({
  Key? key,
  int flex = 1,
})

ClipRect clipRect({...})

将一个小部件包裹在一个ClipRect中。

ClipRect clipRect({
  Key? key,
  CustomClipper<Rect>? clipper,
  Clip clipBehavior = Clip.hardEdge,
})

ClipRRect clipRRect({...})

将一个小部件包裹在一个ClipRRect中。

ClipRRect clipRRect({
  Key? key,
  BorderRadiusGeometry borderRadius = BorderRadius.zero,
  CustomClipper<RRect>? clipper,
  Clip clipBehavior = Clip.antiAlias,
})

ClipOval clipOval({...})

将一个小部件包裹在一个ClipOval中。

ClipOval clipOval({
  Key? key,
  CustomClipper<Rect>? clipper,
  Clip clipBehavior = Clip.antiAlias,
})

ClipPath clipPath({...})

将一个小部件包裹在一个ClipPath中。

ClipPath clipPath({
  Key? key,
  CustomClipper<Path>? clipper,
  Clip clipBehavior = Clip.antiAlias,
})

InkWell inkWell({...})

将一个小部件包裹在一个InkWell中。

InkWell inkWell({
  Key? key,
  void Function()? onTap,
  void Function()? onDoubleTap,
  void Function()? onLongPress,
  void Function(TapDownDetails)? onTapDown,
  void Function(TapUpDetails)? onTapUp,
  void Function()? onTapCancel,
  void Function()? onSecondaryTap,
  void Function(TapUpDetails)? onSecondaryTapUp,
  void Function(TapDownDetails)? onSecondaryTapDown,
  void Function()? onSecondaryTapCancel,
  void Function(bool)? onHighlightChanged,
  void Function(bool)? onHover,
  MouseCursor? mouseCursor,
  Color? focusColor,
  Color? hoverColor,
  Color? highlightColor,
  MaterialStateProperty<Color?>? overlayColor,
  Color? splashColor,
  InteractiveInkFeatureFactory? splashFactory,
  double? radius,
  BorderRadius? borderRadius,
  ShapeBorder? customBorder,
  bool? enableFeedback = true,
  bool excludeFromSemantics = false,
  FocusNode? focusNode,
  bool canRequestFocus = true,
  void Function(bool)? onFocusChange,
  bool autofocus = false,
  MaterialStatesController? statesController,
})

SingleChildScrollView singleChildScrollView({...})

将一个小部件包裹在一个SingleChildScrollView中。

SingleChildScrollView singleChildScrollView({
  Key? key,
  Axis scrollDirection = Axis.vertical,
  bool reverse = false,
  EdgeInsetsGeometry? padding,
  bool? primary,
  ScrollPhysics? physics,
  ScrollController? controller,
  DragStartBehavior dragStartBehavior = DragStartBehavior.start,
  Clip clipBehavior = Clip.hardEdge,
  String? restorationId,
  ScrollViewKeyboardDismissBehavior keyboardDismissBehavior =
      ScrollViewKeyboardDismissBehavior.manual,
})

Align align({...})

将一个小部件包裹在一个Align中。

Align align({
  Key? key,
  AlignmentGeometry alignment = Alignment.center,
  double? widthFactor,
  double? heightFactor,
})

Positioned positioned({...})

将一个小部件包裹在一个Positioned中。

Positioned positioned({
  Key? key,
  double? left,
  double? top,
  double? right,
  double? bottom,
  double? width,
  double? height,
})

Center center({...})

将一个小部件包裹在一个Center中。

Center center({
  Key? key,
  double? widthFactor,
  double? heightFactor,
})

更多关于Flutter扩展小部件插件some_widget_extensions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter扩展小部件插件some_widget_extensions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中使用假设的some_widget_extensions插件的代码示例。请注意,由于some_widget_extensions是一个假设的插件,实际的插件功能和API可能有所不同。但以下示例将展示如何导入和使用一个典型的Flutter插件。

首先,确保你的Flutter项目中已经添加了some_widget_extensions插件。你可以在pubspec.yaml文件中添加以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  some_widget_extensions: ^x.y.z  # 请替换为实际的版本号

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

接下来,在你的Flutter应用程序中导入并使用该插件。以下是一个简单的示例,展示了如何使用some_widget_extensions插件(假设它提供了一些扩展的小部件):

import 'package:flutter/material.dart';
import 'package:some_widget_extensions/some_widget_extensions.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 StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter some_widget_extensions Demo'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            // 假设some_widget_extensions提供了一个ExtendedButton小部件
            ExtendedButton(
              text: 'Click Me',
              onPressed: () {
                print('Button clicked!');
              },
              // 假设还有其他属性可以配置
              color: Colors.green,
              fontSize: 20,
            ),
            
            // 假设还有一个ExtendedTextField小部件
            ExtendedTextField(
              hintText: 'Enter text here',
              onChanged: (value) {
                print('Text changed to: $value');
              },
              // 假设还有其他属性可以配置
              borderColor: Colors.red,
              borderRadius: BorderRadius.circular(10),
            ),
          ],
        ),
      ),
    );
  }
}

// 假设ExtendedButton和ExtendedTextField是some_widget_extensions提供的自定义小部件
// 这里只是示意性的定义,实际使用时请参考插件的文档
class ExtendedButton extends StatelessWidget {
  final String text;
  final VoidCallback onPressed;
  final Color color;
  final double fontSize;

  ExtendedButton({required this.text, required this.onPressed, this.color = Colors.blue, this.fontSize = 16});

  @override
  Widget build(BuildContext context) {
    return ElevatedButton(
      onPressed: onPressed,
      style: ButtonStyle(
        backgroundColor: MaterialStateProperty.all(color),
        overlayColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
          if (states.contains(MaterialState.pressed)) {
            return color.withAlpha(130);
          }
          return null;
        }),
      ),
      child: Text(
        text,
        style: TextStyle(fontSize: fontSize),
      ),
    );
  }
}

class ExtendedTextField extends StatelessWidget {
  final String hintText;
  final ValueChanged<String> onChanged;
  final Color borderColor;
  final BorderRadius borderRadius;

  ExtendedTextField({required this.hintText, required this.onChanged, this.borderColor = Colors.grey, this.borderRadius = BorderRadius.circular(4)});

  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: InputDecoration(
        border: OutlineInputBorder(
          borderRadius: borderRadius,
          borderSide: BorderSide(color: borderColor),
        ),
        hintText: hintText,
      ),
      onChanged: onChanged,
    );
  }
}

注意

  1. 上面的ExtendedButtonExtendedTextField只是示例性的定义,实际使用时请参考some_widget_extensions插件的文档。
  2. 插件可能提供了更多的小部件和功能,请参考其官方文档和示例代码。

希望这个示例能够帮助你开始使用some_widget_extensions插件!

回到顶部