简体   繁体   English

如何设置Flutter中Row()的背景色?

[英]How to set the background color of a Row() in Flutter?

I'm trying to set up a background color for a Row() widget, but Row itself has no background color or color attribute.我正在尝试为 Row() 小部件设置背景颜色,但 Row 本身没有背景颜色或颜色属性。 I've been able to set the background color of a container to grey, right before the purple-backgrounded text, but the text itself does not fill the background completely and the following spacer does not take any color at all.我已经能够将容器的背景颜色设置为灰色,就在紫色背景文本之前,但是文本本身并没有完全填充背景,并且下面的间隔符根本没有任何颜色。

So how can I have the Row background set to the "HexColor(COLOR_LIGHT_GREY)" value so it spans over the whole row?那么如何将行背景设置为“HexColor(COLOR_LIGHT_GREY)”值,使其跨越整行?

Any idea?任何的想法? Thanks a lot!非常感谢!

在此处输入图像描述

Here's the code that I have so far:这是我到目前为止的代码:

import 'package:flutter/material.dart';
import '../manager/ShoppingListManager.dart';
import '../model/ShoppingListModel.dart';
import '../hexColor.dart';
import '../Constants.dart';

class ShoppingListWidget extends StatelessWidget {
  final Color color = Colors.amberAccent;
  final int shoppingListIndex;

  ShoppingListWidget({this.shoppingListIndex});

  @override
  Widget build(BuildContext context) {
    ShoppingListManager slm = new ShoppingListManager();
    String shoppingListName =
        slm.myShoppingLists.shoppingLists[shoppingListIndex].name;
    int categoryCount =
        slm.myShoppingLists.shoppingLists[shoppingListIndex].categories.length;

    return Scaffold(
      appBar: AppBar(
        title: Text(shoppingListName),
        automaticallyImplyLeading: true,
      ),
      body: ListView.builder(
        itemBuilder: (context, index) {
          Category cat = slm.myShoppingLists.shoppingLists[shoppingListIndex]
              .categories[index];

          return Container(
            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.grey[500]),
              color: Colors.white,
            ),
            child: new Column(
              children: <Widget>[
                getCategoryWidget(context, cat),
                getCategoryItems(context, cat),
              ],
            ),
          );
        },
        itemCount: categoryCount,
      ),
    );
  }

  // Render the category "headline" row where I want to set the background color
  // to HexColor(COLOR_LIGHT_GREY)
  Widget getCategoryWidget(BuildContext context, Category cat) {
    return new Row(
      children: <Widget>[
        new Container(height: 40.0, width: 10.0, color: HexColor(cat.color)),
        new Container(
            height: 40.0, width: 15.0, color: HexColor(COLOR_LIGHT_GREY)),
        new Container(
          child: new Text("Category", textAlign: TextAlign.start,
            style: TextStyle(
                fontFamily: 'Bold',
                fontSize: 18.0,
                color: Colors.black),
          ),
          decoration: new BoxDecoration(
            color: Colors.purple,
          ),
          height: 40.0,
        ),
        Spacer(),

        CircleAvatar(
          backgroundImage:
              new AssetImage('assets/icons/food/food_settings.png'),
          backgroundColor: HexColor(COLOR_LIGHT_GREY),
          radius: 15.0,
        ),
        new Container(height: 15.0, width: 10.0, color: Colors.transparent),
      ],
    );
  }

  // render the category items
  Widget getCategoryItems(BuildContext context, Category cat) {
    return ListView.builder(
      itemBuilder: (context, index) {
        String itemName = "Subcategory";
        return new Row(children: <Widget>[
          new Container(height: 40.0, width: 5.0, color: HexColor(cat.color)),
          new Container(height: 40.0, width: 20.0, color: Colors.white),
          new Container(
            child: new Text(itemName),
              color: Colors.white,
          ),
          Spacer()
        ]);
      },
      itemCount: cat.items.length,
      shrinkWrap: true,
      physics:
          ClampingScrollPhysics(),
    );
  }

}

Just wrap your Row with a Container with colour property like below:只需使用具有颜色属性的 Container 将您的 Row 包裹起来,如下所示:

   Container(
            color: Colors.black,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Text('Demo', style: TextStyle(color: Colors.white),),
                )
              ],
            ),
          )

Update:更新:

Since Flutter 2.0, the Container is optimized and give the same performance as a regular ColoredBox .自 Flutter 2.0 起, Container进行了优化,并提供与常规ColoredBox相同的性能。

Wrap your Row in a Container and give it a color .将您的Row包裹在Container并为其指定color

Container(
  color: Colors.red,
  child: Row(children: []),
)

Old:老的:

Use ColoredBox instead of a Container for more efficiency.使用ColoredBox而不是Container以提高效率。

Using Container results in a widget heirarchy that uses a BoxDecoration to actually paint the background color.使用 Container 会产生一个使用 BoxDecoration 来实际绘制背景颜色的小部件层次结构。 The BoxDecoration widget covers many cases other than just painting a background color, and is not as efficient as the new ColoredBox widget, which only paints a background color. BoxDecoration 小部件涵盖了许多情况,而不仅仅是绘制背景颜色,并且不如新的 ColoredBox 小部件高效,后者只绘制背景颜色。 Source 来源

ColoredBox(
  color: Colors.red,
  child: Row(children: []),
)

You can try this, it will work.你可以试试这个,它会起作用。

return DataRow.byIndex(
          index: row.key,
          color: MaterialStateColor.resolveWith(
            (states) {
              if (row.key % 2 == 0) {
                return Colors.blue[50];
              } else {
                return Colors.white;
              }
            },
          ),

I use my own custom row and column with so may customizable options:我使用我自己的自定义行和列以及可自定义的选项:

Widget column({
  final EdgeInsets padding = EdgeInsets.zero,
  final EdgeInsets margin = EdgeInsets.zero,
  final List<Widget> children = const <Widget>[],
  final MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
  final MainAxisSize mainAxisSize = MainAxisSize.max,
  final CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
  final VerticalDirection verticalDirection = VerticalDirection.down,
  final BoxDecoration? decoration,
  final double? width,
  final double? height,
  final bool isScrollable = false,
  final VoidCallback? onTap,
}) =>
    Container(
      width: width,
      height: height,
      decoration: decoration,
      padding: padding,
      margin: margin,
      child: isScrollable
          ? SingleChildScrollView(
              child: Column(
                mainAxisAlignment: mainAxisAlignment,
                mainAxisSize: mainAxisSize,
                crossAxisAlignment: crossAxisAlignment,
                verticalDirection: verticalDirection,
                children: children,
              ),
            )
          : GestureDetector(
              onTap: onTap,
              child: Column(
                mainAxisAlignment: mainAxisAlignment,
                mainAxisSize: mainAxisSize,
                crossAxisAlignment: crossAxisAlignment,
                verticalDirection: verticalDirection,
                children: children,
              ),
            ),
    );

Widget row({
  final EdgeInsets padding = EdgeInsets.zero,
  final EdgeInsets margin = EdgeInsets.zero,
  final List<Widget> children = const <Widget>[],
  final MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
  final MainAxisSize mainAxisSize = MainAxisSize.max,
  final CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
  final VerticalDirection verticalDirection = VerticalDirection.down,
  final BoxDecoration? decoration,
  final double? width,
  final double? height,
  final bool isScrollable = false,
  final VoidCallback? onTap,
}) =>
    Container(
      width: width,
      height: height,
      decoration: decoration,
      padding: padding,
      margin: margin,
      child: isScrollable
          ? SingleChildScrollView(
              child: Row(
                mainAxisAlignment: mainAxisAlignment,
                mainAxisSize: mainAxisSize,
                crossAxisAlignment: crossAxisAlignment,
                verticalDirection: verticalDirection,
                children: children,
              ),
            )
          : GestureDetector(
              onTap: onTap,
              child: Row(
                mainAxisAlignment: mainAxisAlignment,
                mainAxisSize: mainAxisSize,
                crossAxisAlignment: crossAxisAlignment,
                verticalDirection: verticalDirection,
                children: children,
              ),
            ),
    );

You can simply use ListTile and set the tile color like:您可以简单地使用 ListTile 并将图块颜色设置为:

return const ListTile( title: Text('This is a text'), tileColor: Colors.lightBlue, );

It will change the color of whole row in a ListView它将改变 ListView 中整行的颜色

Or you can also add a BoxDecoration to the TableRow.或者您也可以向 TableRow 添加一个 BoxDecoration。

Then add the background color as the color property to the BoxDecoration on the TableRow.然后将背景颜色作为颜色属性添加到 TableRow 上的 BoxDecoration。

Table(
    border: TableBorder.all(),
    children: pairs
        .asMap()
        .map((index, pair) => MapEntry(
            index,
            TableRow(
                decoration: BoxDecoration(
                  color: Theme.of(context)
                      .accentColor // Background color for the row
                      .withOpacity(index % 2 == 0 ? 1.0 : 0.5), // To alternate between dark and light shades of the row's background color.
                ),
                children: [
                  Padding(
                    padding: const EdgeInsets.all(kDefaultMargin / 2),
                    child: Text(
                      pair.first,
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(kDefaultMargin / 2),
                    child: Text(pair.second),
                  )
                ])))
        .values
        .toList()
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM