美文网首页
Flutter SDK 自带的 10 个最有用的 Widget

Flutter SDK 自带的 10 个最有用的 Widget

作者: 蜗牛是不是牛 | 来源:发表于2023-10-31 16:10 被阅读0次

    前言

    在这里我将分享最有用的 Flutter SDK 自带 Widget

    1. Slider

    我们使用滑块小部件来更改值。因此,需要将值存储在变量中。这个小部件有一个滑块类,它需要 onChanged ()函数。当我们改变滑块位置时,这个函数将被调用。

    示例代码

      Slider(
          value: _value.toDouble(),
          min: 1.0,
          max: 20.0,
          divisions: 10,
          activeColor: AppColors.mainColor,
          inactiveColor: Colors.grey.shade400,
          label: 'Set volume value',
          onChanged: (double newValue) {
            setState(() {
              _value = newValue.round();
            });
          },
          semanticFormatterCallback: (double newValue) {
            return '${newValue.round()} dollars';
          })),
    

    2. Range Slider

    它是一个高度可定制的组件,可以从一系列值中选择一个值。它可以从一组连续的或离散的值中进行选择。

    示例代码

      RangeSlider(
        values: _currentRangeValues,
        min: 0,
        max: 100,
        activeColor: AppColors.mainColor,
        inactiveColor: Colors.grey.shade400,
        divisions: 10,
        labels: RangeLabels(
          _currentRangeValues.start.round().toString(),
          _currentRangeValues.end.round().toString(),
        ),
        onChanged: (RangeValues values) {
          setState(() {
            _currentRangeValues = values;
          });
        },
    

    3. Single Chip

    芯片是一个 Material 设计小部件,内置 Flutter 。它可以简单地描述为一个包含图标和文本(通常是背景中的圆角矩形)的紧凑元素。它可以有很多用途,比如它可以简单地用作一个按钮,用 CircleAvatar 和文本表示用户,或者在博客文章中使用主题标签等等。

    示例代码

      Chip(
        padding:
            const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        avatar: const CircleAvatar(
          backgroundColor: AppColors.mainColor,
          child: Text("D"),
        ),
        label: const Text("Dev"),
        onDeleted: () {},
      ),
    

    4. Multiple Chip

    我们可以使用小部件芯片(过滤,显示多个芯片,选择或删除芯片,等等)。让我们看看这个例子。

    示例代码

    GridView.count(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        crossAxisCount: 3,
        childAspectRatio: 4,
        crossAxisSpacing: 5.0,
        mainAxisSpacing: 5.0,
        children: List.generate(nameList.length, (index) {
          return Chip(
            padding: const EdgeInsets.symmetric(
                horizontal: 12, vertical: 6),
            avatar: CircleAvatar(
              backgroundColor: AppColors.mainColor,
              child: Text(nameList[index].substring(0, 1)),
            ),
            label: Text(nameList[index]),
            onDeleted: () {
              setState(() {
                nameList.removeAt(index);
              });
            },
          );
        })),
    

    5. Spacer

    Spacer 创建一个可调节的空间隔,可用于调整 Flex 容器(如 Row 或 Column)中小部件之间的间距。Spacer 小部件将占用所有可用空间,因此设置 Flex。在包含到 MainAxisAlign 的间隔的 flex 容器上进行 mainAxisAlign。

    [图片上传失败...(image-16a3ff-1698826191278)]

    示例代码

      const Spacer(),
      Container(
        width: MediaQuery.of(context).size.width / 1,
        height: 100,
        color: AppColors.mainColor,
      ),
      const Spacer(),
      Container(
        width: MediaQuery.of(context).size.width / 1,
        height: 100,
        color: AppColors.mainColor,
      ),
      const Spacer(),
      Container(
        width: MediaQuery.of(context).size.width / 1,
        height: 100,
        color: AppColors.mainColor,
      ),
      const Spacer(),
    

    6. Floating Action Button & BottomAppBar

    让我们容易做到这一点!

    @override
      Widget build(BuildContext context) {
        return Scaffold(
            body: CustomScrollView(
          slivers: <Widget>[
            SliverAppBar(
              snap: false,
              pinned: true, // it will pinned the app bar on top
              floating: false,
              flexibleSpace: const FlexibleSpaceBar(
                centerTitle: false,
                title: Text("Awesome Sliver AppBar",
                    style: TextStyle(
                      color: AppColors.whiteColor,
                      fontSize: 15.0,
                    )),
                // background: ,
                // Here you can use any image or gif in background
              ),
              expandedHeight: 230,// fix the expanded height of the app bar
              backgroundColor: AppColors.mainColor, // backgroundcolor of the expanded appbar and normal appbar ( for both )
              leading: IconButton(
                icon: const Icon(Icons.menu),
                tooltip: 'Menu',
                onPressed: () {},
              ),
              actions: <Widget>[
                IconButton(
                  icon: const Icon(Icons.notifications_active),
                  tooltip: 'Comment Icon',
                  onPressed: () {},
                ),
                IconButton(
                  icon: const Icon(Icons.chat),
                  tooltip: 'Setting Icon',
                  onPressed: () {},
                ),
              ],
            ),
            SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) => Padding(
                  padding: const EdgeInsets.all(15.0),
                  child: Container(
                    height: MediaQuery.of(context).size.height / 5,
                    width: MediaQuery.of(context).size.width / 1,
                    decoration: BoxDecoration(
                        color: AppColors.cyanColor,
                        borderRadius: BorderRadius.circular(30)),
                  ),
                ),
                childCount: 8,
              ),
            )
          ],
        ));
      }
    

    6. Material Banner

    • banner 容器的形状是矩形的,它扩展了完整的小部件。
    • 这个容器有一个前导图标、文本和操作按钮。
    • 一个 banner 可以包含两个文本按钮,左边是解散操作按钮,右边是确认操作按钮。
    • Material banner 小部件是在 2.5.0 版本中引入的,因此要使用这个小部件,我们需要最新版本。

    [图片上传失败...(image-3cf3a7-1698826191279)]

    示例代码

    MaterialBanner(
      content: const Text('Your account has been deleted.'),
      leading: const CircleAvatar(
        child: Icon(Icons.account_box),
      ),
      actions: <Widget>[
        TextButton(
          child: const Text('UNDO'),
          onPressed: () {
            // Perform some action.
          },
        ),
        TextButton(
          child: const Text('DISMISS'),
          onPressed: () {
            // Perform some action.
          },
        ),
      ],
    ),
    

    7. CheckboxListTile

    CheckboxListTile 是一个内置的小部件。我们可以说它是 CheckBox 和 ListTile 的组合。它的属性,例如 value、 activeColor 和 checkColor,与 CheckBox 小部件相似,title、 subtitle、 contentPadd 等与 ListTile 小部件相似。我们可以点击 CheckBoxListTile 上的任何地方来 Google 这个复选框。

    [图片上传失败...(image-663a0e-1698826191279)]

      CheckboxListTile(
        value: isChecked,
        onChanged: (bool? newValue) {
          setState(() {
            isChecked = newValue;
          });
        },
        title: const Text("Checkbox List Tile"),
        activeColor: Colors.orange,
        checkColor: Colors.white,
        tileColor: Colors.black12,
        subtitle: const Text('This is a subtitle'),
        controlAffinity: ListTileControlAffinity.leading,
        tristate: true,
      )
    

    8. Table

    表小部件用于在表布局中显示项。不需要使用行和列来创建表。如果有多个行具有相同的列宽,那么 Table 小部件是正确的方法。

    [图片上传失败...(image-e95263-1698826191279)]

      Table(
        textDirection: TextDirection.rtl,
        defaultVerticalAlignment: TableCellVerticalAlignment.middle,
        border:
            TableBorder.all(width: 2.0, color: AppColors.blackColor),
        // ignore: prefer_const_literals_to_create_immutables
        children: [
          const TableRow(
              decoration: BoxDecoration(
                color: AppColors.mainColor,
              ),
              children: [
                TableCell(
                  verticalAlignment: TableCellVerticalAlignment.middle,
                  child: Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text(
                      "Name",
                      style: TextStyle(color: AppColors.whiteColor),
                      textScaleFactor: 1.1,
                    ),
                  ),
                ),
                TableCell(
                  verticalAlignment: TableCellVerticalAlignment.middle,
                  child: Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text(
                      "Number",
                      style: TextStyle(color: AppColors.whiteColor),
                      textScaleFactor: 1.1,
                    ),
                  ),
                ),
                TableCell(
                  verticalAlignment: TableCellVerticalAlignment.middle,
                  child: Padding(
                    padding: EdgeInsets.all(8.0),
                    child: Text(
                      "Grade",
                      style: TextStyle(color: AppColors.whiteColor),
                      textScaleFactor: 1.1,
                    ),
                  ),
                ),
              ]),
          ...List.generate(
              7,
              (index) => const TableRow(children: [
                    TableCell(
                      verticalAlignment:
                          TableCellVerticalAlignment.middle,
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Text(
                          "Name",
                          style: TextStyle(
                              fontSize: 14,
                              color: AppColors.blackColor),
                          textScaleFactor: 1,
                        ),
                      ),
                    ),
                    TableCell(
                      verticalAlignment:
                          TableCellVerticalAlignment.middle,
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Text(
                          "Number",
                          style: TextStyle(
                              fontSize: 14,
                              color: AppColors.blackColor),
                          textScaleFactor: 1,
                        ),
                      ),
                    ),
                    TableCell(
                      verticalAlignment:
                          TableCellVerticalAlignment.middle,
                      child: Padding(
                        padding: EdgeInsets.all(8.0),
                        child: Text(
                          "Grade",
                          style: TextStyle(
                              fontSize: 14,
                              color: AppColors.blackColor),
                          textScaleFactor: 1,
                        ),
                      ),
                    ),
                  ]))
        ],
      ),
    

    9. Grid Tile

    Flutter 中的 GridTile 是无状态小部件的一个子类,它是一个可滚动的瓦片网格。

    Center(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10),
        child: SizedBox(
          height: MediaQuery.of(context).size.height / 3,
          width: MediaQuery.of(context).size.width / 2,
          child: GridTile(
            // header: const GridTileBar(
            //   backgroundColor: Colors.blueGrey,
            //   title: Text(
            //     "Product Title",
            //     textAlign: TextAlign.center,
            //   ),
            // ),
            child: GestureDetector(
                onTap: () {},
                child: Container(
                  color: Colors.black12,
                )),
            footer: GridTileBar(
              backgroundColor: Colors.blueGrey,
              leading: IconButton(
                icon: const Icon(Icons.favorite),
                color: Colors.white,
                onPressed: () {},
              ),
              title: const Text(
                "Title",
                textAlign: TextAlign.center,
              ),
              trailing: IconButton(
                icon: const Icon(
                  Icons.shopping_cart,
                ),
                onPressed: () {},
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    ),
    

    10. Selectable Text

    SelectableText 小部件显示具有单个样式的文本字符串。根据布局约束,字符串可以跨多行显示,也可以全部显示在同一行上。

    SelectableText('This is selectable Text',
      style: const TextStyle(fontSize: 22),
      onSelectionChanged: (selection, cause) {},
    ),
    

    完整源代码 github.com/kaushikikum…


    相关文章

      网友评论

          本文标题:Flutter SDK 自带的 10 个最有用的 Widget

          本文链接:https://www.haomeiwen.com/subject/txziidtx.html