Flutter构建上下文管理插件simple_build_context的使用

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

Flutter构建上下文管理插件simple_build_context的使用

License: MIT Nombre del paquete Dart 3 Flutter 3.10

累了在Flutter应用中传递context吗?我们的库简化了这一过程,通过提供一个易于使用的context包装器,可以轻松地在整个代码库中访问。使用我们的库,您可以简化代码并提高应用的可读性,同时享受更高效的开发流程。我们的context库提供了独特的功能,使其与其他市场上的类似库区分开来,包括与流行的Flutter包(如Provider)无缝集成,并且可以在代码库的任何地方访问context。使用我们的库,您可以专注于开发您的应用,而不是担心context管理的复杂性。

开始使用

TODO: 列出先决条件并提供或指向有关如何开始使用该包的信息。

安装

要安装simple_build_context,在pubspec.yaml文件中添加以下依赖项:

dependencies:
  simple_build_context: ^1.0.9

然后在命令行中运行 flutter pub get

使用

导入库:

import 'package:simple_build_context/src/config_build_context.dart';

可用扩展

DateTime

  • context.now

FocusScope.of(context)

  • context.focusScope.hasFocus
  • context.focusScope.isFirstFocus
  • context.focusScope.hasPrimaryFocus
  • context.focusScope.canRequestFocus
  • context.focusScope.nextFocus()
  • context.focusScope.requestFocus()
  • context.focusScope.previousFocus()
  • context.focusScope.unFocus()
  • context.focusScope.setFirstFocus()
  • context.focusScope.consumeKeyboardToken()

Form.of(context)

  • context.form.validate()
  • context.form.reset()
  • context.form.save()

MediaQuery

  • context.mediaQuerySize
  • context.mediaQueryPadding
  • context.mediaQueryViewPadding
  • context.mediaQueryViewInsets
  • context.orientation
  • context.isLandscape
  • context.isPortrait
  • context.alwaysUse24HourFormat
  • context.devicePixelRatio
  • context.platformBrightness
  • context.textScaleFactor
  • context.mediaQueryShortestSide
  • context.mediaQueryLongestSide
  • context.mediaQueryAspectRatio
  • context.invertColors
  • context.disableAnimations
  • context.accessibleNavigation
  • context.isPhone
  • context.isSmallTablet
  • context.isLargeTablet
  • context.isTablet
  • context.screenWidth
  • context.screenHeight
  • context.isLandscapeMode
  • context.isPortraitMode
  • context.bottomNavigationBarHeight
  • context.statusBarHeight
  • context.systemGestureInsetBottom
  • context.horizontalPadding
  • context.verticalPadding
  • context.allPadding
  • context.isHighContrast
  • context.isInteractive

ModalRoute

  • context.modalRoute
  • context.routeSettings
  • context.scaffold
  • context.isScaffoldOpen

Navigator

  • context.push()
  • context.pop()
  • context.pushNamed()
  • context.canPop()
  • context.popUntil()

Navigator (Variant)

  • context.navigateTo()
  • context.navigateToNamed()
  • context.navigateBack()

Random

  • context.nextInt()

Scaffold

  • context.showSnackBar()
  • context.removeCurrentSnackBar()
  • context.hideCurrentSnackBar()
  • context.openDrawer()
  • context.openEndDrawer()
  • context.showBottomSheet()
  • context.showBottomSheet()
  • context.isScaffoldDrawerOpen
  • context.isScaffoldEndDrawerOpen

Theme

  • context.theme
  • context.textTheme
  • context.primaryTextTheme
  • context.bottomAppBarTheme
  • context.bottomSheetTheme
  • context.backgroundColor
  • context.onPrimary
  • context.onBackground
  • context.primaryColor
  • context.scaffoldBackgroundColor
  • context.appBarTheme
  • context.platform
  • context.isAndroid
  • context.isIOS
  • context.isMacOS
  • context.isWindows
  • context.isFuchsia
  • context.isLinux
  • context.headline1
  • context.headline2
  • context.headline3
  • context.headline4
  • context.headline5
  • context.headline6
  • context.subtitleMedium
  • context.subtitleSmall
  • context.bodyTextLarge
  • context.bodyTextMedium
  • context.caption
  • context.labelButtonLarge
  • context.everLineSmall
  • context.cardColor
  • context.dividerColor
  • context.errorColor
  • context.focusColor
  • context.highlightColor
  • context.splashColor
  • context.overLine
  • context.button
  • context.subtitle1
  • context.subtitle2
  • context.bodyText1
  • context.bodyText2
  • context.cardTitle
  • context.errorText
  • context.textFieldLabel
  • context.disabledTextStyle
  • context.tabBarTextStyle
  • context.disabledColor
  • context.hintColor
  • context.primaryColorLight
  • context.secondaryColor
  • context.secondaryColorDark
  • context.tertiaryColor
  • context.tertiaryColorLight
  • context.tertiaryColorDark
  • context.successColor
  • context.warningColor
  • context.titleFontSize
  • context.subtitleFontSize
  • context.bodyFontSize
  • context.captionFontSize
  • context.buttonFontSize
  • context.overLineFontSize
  • context.appBarHeight
  • context.cardHeight
  • context.cardWidth
  • context.cardRadius
  • context.isLightTheme
  • context.isDarkTheme
  • context.iconSize
  • context.buttonPadding
  • context.inputDecorationPadding
  • context.iconButtonSize
  • context.iconButtonRadius

ScrollController

  • context.primaryScrollController

String

String? nullText = null;
bool isNullOrEmpty = nullText?.isNullOrEmpty ?? true; // 返回true
bool isNotNullOrEmpty = nullText?.isNotNullOrEmpty ?? false; // 返回false

String emptyText = '';
bool isNullOrEmpty = emptyText.isNullOrEmpty; // 返回true
bool isNotNullOrEmpty = emptyText.isNotNullOrEmpty; // 返回false

String notEmptyText = 'Hello, mundo!';
bool isNullOrEmpty = notEmptyText.isNullOrEmpty; // 返回false
bool isNotNullOrEmpty = notEmptyText.isNotNullOrEmpty; // 返回true

Widget

/// 在代码中最小化if条件
class MyWidget extends StatelessWidget {
  final String? text;

  const MyWidget({Key? key, this.text}) : super(key: key);

  [@override](/user/override)
  Widget build(BuildContext context) {
    // 检查文本是否不为空
    final isTextNotEmpty = text.isNotNullOrEmpty;

    // 如果文本不为空,则构建一个文本小部件,否则构建一个圆形进度指示器
    final widget = isTextNotEmpty
        ? Text(text!)
        : CircularProgressIndicator();

    // 检查小部件是否为null
    final isWidgetNull = widget.isNull;

    // 如果小部件为null,则提供一个替代的小部件
    final widgetOrDefault = widget.orElse(Container());

    // 构建一个列小部件,显示小部件(如果它不为null或空),否则显示错误消息
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        widgetOrDefault,
        if (isWidgetNull)
          Text('The widget is null')
        else if (!isTextNotEmpty)
          Text('The text is null or empty')
      ],
    );
  }
}

Iterable

List<int> numbers = [1, 2, 3, 4, 5];
List<int> listOfNumbers = numbers.asList; // 返回一个新的包含numbers元素的列表

String? text = ['hello', 'world'].firstOrNull; // 返回'hello'
Set<int> sets = {};
int? lastElement = sets.lastOrNull; // 返回null

List

List<int> numbers = [1, 2, 3, 4, 5];
int? lastNumber = numbers.lastOrNull; // 返回5
int? firstNumber = numbers.firstOrNull; // 返回1

List<String> letter = ['a', 'b', 'c', 'd'];
List<String> subList = letter - ['a', 'c']; // 返回['b', 'd']

示例

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

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: context.scaffoldBackgroundColor,
      body: Center(
        child: ElevatedButton(
          onPressed: () => context.pushNamed('/pageRoute'),
          child: Text(
            'NextPage',
            style: context.primaryTextTheme.titleMedium,
          ),
        ),
      ),
    );
  }
}

更多关于Flutter构建上下文管理插件simple_build_context的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter构建上下文管理插件simple_build_context的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter中使用simple_build_context插件进行上下文管理的代码示例。假设你已经添加了simple_build_context到你的pubspec.yaml文件中,并且已经运行了flutter pub get

首先,确保你的pubspec.yaml中包含以下依赖项:

dependencies:
  flutter:
    sdk: flutter
  simple_build_context: ^最新版本号  # 请替换为实际最新版本号

然后,你可以按照以下步骤在你的Flutter应用中使用simple_build_context插件。

1. 导入插件

在你的Dart文件中导入simple_build_context插件:

import 'package:simple_build_context/simple_build_context.dart';

2. 使用BuildContextProviderBuildContextConsumer

simple_build_context插件通常通过BuildContextProviderBuildContextConsumer来管理上下文。以下是一个简单的示例,展示如何在父组件中提供上下文,并在子组件中消费它。

import 'package:flutter/material.dart';
import 'package:simple_build_context/simple_build_context.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: Scaffold(
        appBar: AppBar(
          title: Text('Simple Build Context Demo'),
        ),
        body: BuildContextProvider<String>(
          create: () => 'Hello from Provider!',
          child: MyHomePage(),
        ),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            'You have pushed the button this many times:',
          ),
          BuildContextConsumer<String>(
            builder: (context, value) {
              return Text(
                value,
                style: Theme.of(context).textTheme.headline4,
              );
            },
          ),
        ],
      ),
    );
  }
}

在这个示例中:

  • BuildContextProvider<String> 用于创建一个上下文并提供一个字符串值。
  • create 参数是一个函数,用于初始化提供的值。
  • BuildContextConsumer<String> 用于消费这个上下文,并通过builder函数显示提供的值。

3. 更新上下文值

如果你需要更新上下文中的值,你可以使用BuildContextProvider.of(context).updateValue(newValue)方法。例如,你可以在按钮点击事件中更新值:

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final BuildContextProvider<String> provider = BuildContextProvider.of<String>(context);
    
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            'You have pushed the button this many times:',
          ),
          BuildContextConsumer<String>(
            builder: (context, value) {
              return Text(
                value,
                style: Theme.of(context).textTheme.headline4,
              );
            },
          ),
          ElevatedButton(
            onPressed: () {
              provider.updateValue('Hello from Button Click!');
            },
            child: Text('Update Context'),
          ),
        ],
      ),
    );
  }
}

在这个示例中,当你点击按钮时,上下文中的字符串值将被更新为Hello from Button Click!

总结

以上示例展示了如何在Flutter应用中使用simple_build_context插件进行上下文管理。通过BuildContextProvider提供上下文,并通过BuildContextConsumer消费上下文,你可以轻松地在组件之间共享和更新数据。

回到顶部