简体   繁体   English

Flutter中如何指定ListTile高度

[英]How to specify ListTile height in Flutter

In this code, I am trying to make a list of buttons or tiles "as buttons do not work well for me " at the very top of the page.在此代码中,我试图在页面顶部制作一个按钮或图块列表,“因为按钮对我来说效果不佳”。 Thus, when one is clicked it returns a value in the rest of the page.因此,当单击一个时,它会在页面的 rest 中返回一个值。

The issue is The tile here toke around more than half of the page which makes it looks inconsistent.问题是这里的图块占据了页面的一半以上,这使得它看起来不一致。 I want to limit the height of the tile, I have tried putting them in a row and a container and it doesn't work.我想限制瓷砖的高度,我试过将它们放在一排和一个容器中,但它不起作用。 Any HELP will be appreciated.任何帮助将不胜感激。

the result after running the code is:运行代码后的结果是:

this is the error after runing the code:这是运行代码后的错误: 在此处输入图像描述

class HomePage extends StatefulWidget {
 // const HomePage({Key key}) : super(key: key);

  @override
  HomePageState createState() {
    return new HomePageState();
  }
}

class HomePageState extends State<HomePage> {
List<String> temp=new List();
List<String> temp1=['Nile University', 'Smart Village', 'Zewail'];
Map<String,String> map1={};
@override
void initState() {
    super.initState();
  getplaces(temp);
  getuser(map1,'1jKpg81YCO5PoFOa2wWR');

  }


Future<List> getuser(temp,String place) async{
  List<String> userids=[];
  QuerySnapshot usersubs= await  Firestore.instance.collection('tempSubs').getDocuments();
  QuerySnapshot userid= await  Firestore.instance.collection('users').where('place',isEqualTo: place).getDocuments();
  userid.documents.forEach((DocumentSnapshot doc,){
  usersubs.documents.forEach((DocumentSnapshot doc1){
    if(doc.documentID==doc1.documentID){
      doc1.data['products'].forEach((k,v){
       
       if( DateTime.fromMillisecondsSinceEpoch(v).day==DateTime.now().day){

        int x= DateTime.fromMillisecondsSinceEpoch(v).day;
                print('keey equal $k and v is $x');

        print('dy is $x');
      userids.add(
      doc.documentID);
       }
      });
      
    }
  } ); }  
    );
              print('doc.documentID');
  print (userids);
   setState(() {});
 return userids;
  }


Future<List> getplaces(temp) async{
    QuerySnapshot place= await  Firestore.instance.collection('places').getDocuments();
  place.documents.forEach((DocumentSnapshot doc){
    temp.add(
      doc.data['name']
    );
            //  print(doc.data['name']);

  });
  //  print(temp);
 
   setState(() {});
 return temp;
  }



  @override
  Widget build(BuildContext context) {
      return Scaffold(
      appBar: AppBar(
         title: Text("Home Page"),
        ),
          
  body: !temp.isNotEmpty? 
   CircularProgressIndicator():  
   Row(mainAxisSize:MainAxisSize.max,
   mainAxisAlignment: MainAxisAlignment.spaceAround,

     children:<Widget>[ 
        Container(
                      height: 100.0,
                      child:
           ListView.builder(
             scrollDirection: Axis.horizontal,
             itemExtent: 100.0,
             itemCount:temp.length,
             itemBuilder:(BuildContext context, int index) {
                return ListTile(title: Text(temp[index]),onTap:
                (){
                  print(temp[index]);
                }
                 );}
     ),),
     Container(child:Text('data'),)
    ],),
       
        );
          
        }
}

Add this one itemExtent in your ListView Properties, itemExtent defines the size of each child.在你的ListView属性中添加这个itemExtentitemExtent定义了每个孩子的大小。 like this ⬇️像这样⬇️

 ListView.builder(
  scrollDirection: Axis.vertical,
  shrinkWrap: true,
  itemCount: 5,
  itemExtent: 50,
  itemBuilder: (context, index) { 
    return TistTile()
  }
 )

And Implementation this one dense:true , in your ListTile Properties, The dense parameter makes the text smaller and packs everything together.并在您的ListTile属性中实现这一点dense:truedense参数使文本更小并将所有内容打包在一起。 like this ⬇️像这样⬇️

  ListTile(
   title: Text("Tony Stark"),
   subtitle: Text("list[index].name",
        style: TextStyle(fontSize: 14.0),),
   contentPadding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 
        16.0),
   dense:true,
   );

You can change how much the content is inset on the left and right (but not the top or bottom) by setting the contentPadding .您可以通过设置contentPadding来更改内容在左侧和右侧(但不是顶部或底部)的插入量。 The default is 16.0 but here we will set to 0.0 :默认值为16.0但在这里我们将设置为0.0

Just remove the Expanded Widget to avoid fill the space available and use a parent Container with a fixed height, the same as the itemExtent value:只需移除Expanded Widget 以避免填充可用空间并使用具有固定高度的父容器,与itemExtent值相同:

    Column(
                  children: <Widget>[
                    Container(
                      height: 100.0,
                      child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          itemExtent: 100.0,
                          itemCount: temp.length,
                          itemBuilder: (BuildContext context, int index) {
                            return ListTile(
                                title: Text(temp[index]),
                                onTap: () {
                                  print(temp[index]);
                                });
                          }),
                    ),
                    Container(
                      child: Text('data'),
                    )
                  ],
                ),

You should use a Container or Padding instead of ListTile if you need more customization.如果您需要更多自定义,您应该使用 Container 或 Padding 而不是 ListTile。

You cannot set the height, but you can make it smaller by setting the dense property to true:您无法设置高度,但可以通过将密集属性设置为 true 来使其更小:

ListView.builder(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          itemCount: list.length,
          itemBuilder: (context, index) {
            return ListTile(
              title: Text(list[index].name,style: TextStyle(fontSize: 20.0),),
              contentPadding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 16.0),
              dense:true,                  
            );
          },
        );

ListTile:列表磁贴:

A single fixed-height row that typically contains some text as well as a leading or trailing icon.单个固定高度的行,通常包含一些文本以及前导或尾随图标。

To be accessible, tappable leading and trailing widgets have to be at least 48x48 in size.要易于访问,可点击的前导和尾随小部件的大小必须至少为 48x48。 However, to adhere to the Material spec, trailing and leading widgets in one-line ListTiles should visually be at most 32 (dense: true) or 40 (dense: false) in height, which may conflict with the accessibility requirement.但是,为了遵守 Material 规范,单行 ListTiles 中的尾随和前导小部件的高度在视觉上最多应为 32(密集:真)或 40(密集:假),这可能与可访问性要求相冲突。

For this reason, a one-line ListTile allows the height of leading and trailing widgets to be constrained by the height of the ListTile.出于这个原因,一行 ListTile 允许前导和尾随小部件的高度受 ListTile 的高度限制。 This allows for the creation of tappable leading and trailing widgets that are large enough, but it is up to the developer to ensure that their widgets follow the Material spec.这允许创建足够大的可点击的前导和尾随小部件,但开发人员需要确保他们的小部件遵循 Material 规范。

https://api.flutter.dev/flutter/material/ListTile-class.htmlhttps://api.flutter.dev/flutter/material/ListTile-class.html

Since there's no height property in ListTile you can limit the size of a tile by placing it inside a SizedBox:由于 ListTile 中没有 height 属性,您可以通过将其放置在 SizedBox 中来限制图块的大小:

          SizedBox(
              height: 32,
              child: ListTile(..))

Applying VisualDensity allows you to expand or contract the height of list tile.应用VisualDensity允许您扩展或收缩列表VisualDensity的高度。 VisualDensity is compactness of UI elements. VisualDensity 是 UI 元素的紧凑性。 Here is an example:下面是一个例子:

// negative value to contract
ListTile(
  title: Text('Tile title'),
  dense: true,
  visualDensity: VisualDensity(vertical: -3), // to compact
  onTap: () {
    // tap actions
  },
)

// positive value to expand
ListTile(
  title: Text('Tile title'),
  dense: true,
  visualDensity: VisualDensity(vertical: 3), // to expand
  onTap: () {
    // tap actions
  },
)

The values ranges from -4 to 4 and default is 0 as of writing this answer.值范围从 -4 到 4,在撰写此答案时默认值为 0。

However, you cannot use this method for specific width or height size.但是,您不能将此方法用于特定的宽度或高度大小。

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

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