📜  Flutter – 有条件地输出小部件

📅  最后修改于: 2021-09-23 06:25:42             🧑  作者: Mango

Flutter是 Google 的 UI 工具包,用于从单个代码库为移动、Web 和桌面构建漂亮的、本地编译的应用程序。 Flutter提供了多种方式来有条件地显示 Widget,在本文中,我们将实现所有方法。

方法 1 :使用If 条件

如果条件为真,这是 flutter 显示小部件的方式。

语法

if (condition) 
  Widget()
Dart
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
  
  /// boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
  
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: [
  
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            /// if the condition is true
            /// [condition == true] then
            /// below Text will be displayed
            if (checked)
              Text(
                'Second Widget',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              )
          ],
        ),
      ),
    );
  }
}


Dart
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
    
/// boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: [
  
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            /// if the condition is true
            /// [condition == true] then
            /// below Text will be displayed
            /// else an [Empty Container] will be displayed
            checked
                ? Text(
                    'Second Widget',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }
}


Dart
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
    
  // boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: [
              
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            // Custom function
            condition(),
          ],
        ),
      ),
    );
  }
  
  // Function
  Widget condition() {
  
    // other logic  
    // Declare a widget variable,
    // it will be assigned later according
    // to the condition
    Widget widget;
  
    // Using switch statement to display desired
    // widget if any certain condition is met
    // You are free to use any condition
    // For simplicity I have used boolean contition
    switch (checked) {
      case true:
        widget = Text(
          'Second Widget',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        );
        break;
      case false:
        widget = Container();
        break;
      default:
        widget = Container();
    }
  
    // Finally returning a Widget
    return widget;
  }
}


Dart
import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State {
  bool _selected;
  
  @override
  void initState() {
    _selected = false;
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 8.0,
                vertical: 16.0,
              ),
  
              /// Checkbox Widget
              child: CheckboxListTile(
                title: Text('Data Structure'),
                value: _selected,
  
                /// Toggling Checkbox value and
                /// assigning it to _selected variable
                onChanged: (value) => setState(() => _selected = value),
              ),
            ),
  
            /// if selected variable is true i.e
            /// [selected == true] then list is visible
            /// otherwise it's not
            if (_selected)
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16.0,
                  vertical: 8.0,
                ),
                child: Container(
                  height: MediaQuery.of(context).size.height * 0.6,
                  child: ListView(
                    children: [
                      Text(
                        'Arrays',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'LinkedList',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'Stack',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'Tree',
                        style: TextStyle(fontSize: 16),
                      )
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}


输出:

方法 2 :使用三元运算符( ? 🙂

您可能在其他语言(如 C++、 Java等)中使用过此运算符。

语法

condition ? Widget() : OtherWidget()

# if condition is true the Widget() is displayed else OtherWidget() is displayed.
Widget and OtherWidget could be any widget even Custom.

Dart

import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
    
/// boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: [
  
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            /// if the condition is true
            /// [condition == true] then
            /// below Text will be displayed
            /// else an [Empty Container] will be displayed
            checked
                ? Text(
                    'Second Widget',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  )
                : Container(),
          ],
        ),
      ),
    );
  }
}

输出:

注意:除了三元运算符,还可以使用if-else条件。这也将产生相同的结果。

方法三自定义函数

如果您想要更多地控制逻辑,那么只需返回一个小部件。您也可以使用自己的函数。在这种方法中,您拥有完全的控制权,因为您可以在显示代码之前随意编写尽可能多的代码。您还可以执行复杂的条件。

Dart

import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatelessWidget {
    
  // boolean variable which is [true]
  final checked = true;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
          
        // AppBar
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: [
              
            // A Simple Text Widget that will be visible
            // all the time
            Text(
              'First Widget',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
  
            // Custom function
            condition(),
          ],
        ),
      ),
    );
  }
  
  // Function
  Widget condition() {
  
    // other logic  
    // Declare a widget variable,
    // it will be assigned later according
    // to the condition
    Widget widget;
  
    // Using switch statement to display desired
    // widget if any certain condition is met
    // You are free to use any condition
    // For simplicity I have used boolean contition
    switch (checked) {
      case true:
        widget = Text(
          'Second Widget',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        );
        break;
      case false:
        widget = Container();
        break;
      default:
        widget = Container();
    }
  
    // Finally returning a Widget
    return widget;
  }
}

输出

下面是一个示例应用程序,用于显示ListView 的条件渲染。

Dart

import 'package:flutter/material.dart';
  
void main() => runApp(MyApp());
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'GeeksforGeeks',
  
      // to hide debug banner
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomePage(),
    );
  }
}
  
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
  
class _HomePageState extends State {
  bool _selected;
  
  @override
  void initState() {
    _selected = false;
    super.initState();
  }
  
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text('GeeksforGeeks'),
        ),
        body: Column(
          children: [
            Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 8.0,
                vertical: 16.0,
              ),
  
              /// Checkbox Widget
              child: CheckboxListTile(
                title: Text('Data Structure'),
                value: _selected,
  
                /// Toggling Checkbox value and
                /// assigning it to _selected variable
                onChanged: (value) => setState(() => _selected = value),
              ),
            ),
  
            /// if selected variable is true i.e
            /// [selected == true] then list is visible
            /// otherwise it's not
            if (_selected)
              Padding(
                padding: const EdgeInsets.symmetric(
                  horizontal: 16.0,
                  vertical: 8.0,
                ),
                child: Container(
                  height: MediaQuery.of(context).size.height * 0.6,
                  child: ListView(
                    children: [
                      Text(
                        'Arrays',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'LinkedList',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'Stack',
                        style: TextStyle(fontSize: 16),
                      ),
                      Text(
                        'Tree',
                        style: TextStyle(fontSize: 16),
                      )
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

输出:

注意:除此之外,如果您想直接在 Column 中显示列表项,则可以使用以下方法:

Column(
  children: [
  
  // some code  
  if (_selected)
    ...[
      Text(
        'Arrays',
        style: TextStyle(fontSize: 16),
      ),
      Text(
        'LinkedList',
        style: TextStyle(fontSize: 16),
      ),
      Text(
        'Stack',
        style: TextStyle(fontSize: 16),
      ),
      Text(
        'Tree',
        style: TextStyle(fontSize: 16),
      )
    ]
    
    // some code 
  ]
..., These strange three dots are spread operator.