Flutter条件渲染插件flutter_conditional_rendering的使用

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

Flutter条件渲染插件flutter_conditional_rendering的使用

flutter_conditional_rendering

flutter_conditional_rendering 是一个增强Flutter条件渲染功能的插件,它支持if-elseswitch条件。

Why

在Flutter中,如果你想进行条件渲染,你可能会这样做:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        if (someCondition == true)
          Text('The condition is true!'),
      ],
    );
  }
}

但是,如果你想要使用三元(if-else)条件呢?

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        someCondition == true ?
          Text('The condition is true!'):
          Text('The condition is false!'),
      ],
    );
  }
}

对于单个Text小部件来说是好的,但是如果子小部件是多层嵌套时,可读性会迅速变差。

Usage

If-Else condition:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Conditional.single(
          context: context,
          conditionBuilder: (BuildContext context) => someCondition == true,
          widgetBuilder: (BuildContext context) => Text('The condition is true!'),
          fallbackBuilder: (BuildContext context) => Text('The condition is false!'),
        ),
      ],
    );
  }
}

Switch condition:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        ConditionalSwitch.single<String>(
          context: context,
          valueBuilder: (BuildContext context) => 'A',
          caseBuilders: {
            'A': (BuildContext context) => Text('The value is A!'),
            'B': (BuildContext context) => Text('The value is B!'),
          },
          fallbackBuilder: (BuildContext context) => Text('None of the cases matched!'),
        ),
      ],
    );
  }
}

Want a list of widgets?

如果你想有条件地渲染一个小部件列表(List<Widget>),请使用Conditional.list()ConditionalSwitch.list()

Contributions

如果你发现了一个bug或者想要一个特性,但不知道如何修复/实现它,请填写一个issue。 如果你修复了一个bug或实现了某个特性,请发送一个pull request

示例代码

下面是一个完整的示例demo,展示了如何使用flutter_conditional_rendering插件来根据计数器的值显示不同的内容:

import 'package:flutter/material.dart';
import 'package:flutter_conditional_rendering/conditional.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            const SizedBox(
              height: 15.0,
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.displayLarge,
            ),
            const SizedBox(
              height: 30.0,
            ),
            Conditional.single(
              context: context,
              conditionBuilder: (BuildContext context) => _counter % 2 == 0,
              widgetBuilder: (BuildContext context) {
                return const Column(
                  children: <Widget>[
                    Text(
                      'The number is even.',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(
                      height: 10.0,
                    ),
                    Icon(
                      Icons.check,
                      size: 60.0,
                      color: Colors.green,
                    ),
                  ],
                );
              },
              fallbackBuilder: (BuildContext context) {
                return const Column(
                  children: <Widget>[
                    Text(
                      'The number is not even.',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    SizedBox(
                      height: 10.0,
                    ),
                    Icon(
                      Icons.close,
                      size: 60.0,
                      color: Colors.red,
                    ),
                  ],
                );
              },
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

这个例子展示了如何使用flutter_conditional_rendering插件来根据计数器的值显示不同的内容。当计数器的值为偶数时,显示“数字是偶数”的文本和绿色的勾号图标;否则,显示“数字不是偶数”的文本和红色的叉号图标。


更多关于Flutter条件渲染插件flutter_conditional_rendering的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter条件渲染插件flutter_conditional_rendering的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,flutter_conditional_rendering 这个插件虽然在 Flutter 社区中不是非常主流或知名,但我们可以根据条件渲染的基本概念来展示如何在 Flutter 中实现条件渲染。通常,Flutter 并不需要一个专门的插件来实现条件渲染,因为它内置了强大的条件逻辑处理功能。

下面是一个简单的 Flutter 应用示例,展示了如何在不使用任何额外插件的情况下实现条件渲染。

示例代码

  1. 创建一个新的 Flutter 项目

    首先,确保你已经安装了 Flutter 和 Dart 开发环境。然后,创建一个新的 Flutter 项目:

    flutter create conditional_rendering_example
    cd conditional_rendering_example
    
  2. 修改 main.dart 文件

    打开 lib/main.dart 文件,并替换其内容为以下代码:

    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Conditional Rendering Example',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: ConditionalRenderingScreen(),
        );
      }
    }
    
    class ConditionalRenderingScreen extends StatefulWidget {
      @override
      _ConditionalRenderingScreenState createState() => _ConditionalRenderingScreenState();
    }
    
    class _ConditionalRenderingScreenState extends State<ConditionalRenderingScreen> {
      bool isConditionMet = false;
    
      void toggleCondition() {
        setState(() {
          isConditionMet = !isConditionMet;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Conditional Rendering Example'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Condition is met: ${isConditionMet.toString()}',
                  style: TextStyle(fontSize: 24),
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: toggleCondition,
                  child: Text('Toggle Condition'),
                ),
                SizedBox(height: 20),
                // 条件渲染
                isConditionMet
                    ? Text(
                        'This text is displayed when the condition is met.',
                        style: TextStyle(color: Colors.green, fontSize: 20),
                      )
                    : Text(
                        'This text is displayed when the condition is not met.',
                        style: TextStyle(color: Colors.red, fontSize: 20),
                      ),
              ],
            ),
          ),
        );
      }
    }
    

解释

  • MyApp:这是应用的根组件,它创建了一个 MaterialApp,并设置了主题和主页为 ConditionalRenderingScreen
  • ConditionalRenderingScreen:这是一个有状态的组件,它包含一个布尔变量 isConditionMet,用于控制条件是否满足。
  • toggleCondition 方法:这个方法使用 setState 来更新 isConditionMet 的值,从而触发组件的重新构建。
  • 条件渲染:在 build 方法中,使用三元运算符 isConditionMet ? WidgetA : WidgetB 来根据 isConditionMet 的值决定显示哪个组件。

通过这种方式,你可以在不使用任何额外插件的情况下,在 Flutter 应用中实现条件渲染。如果你确实需要一个更复杂的条件渲染逻辑库,你可能需要查看 Flutter 社区中更广泛使用的库或自己实现一个。

回到顶部