调整平面按钮的大小并在颤动中提供水平滚动选项

Posted

技术标签:

【中文标题】调整平面按钮的大小并在颤动中提供水平滚动选项【英文标题】:Resize Flat Button and give Horizontal Scrolling option in flutter 【发布时间】:2018-05-15 08:51:15 【问题描述】:

如果您可以在顶部看到,我创建了 4 列,其中包含一个平面按钮,其中包含一个图像和一个文本。我想为 Flat 按钮提供准确的宽度和高度,这可能吗?另外,我想进行水平滚动,以便可以在同一行中添加更多列。此外,单击图像,相应的列表应显示在下方。这是我到目前为止的代码。

     import 'package:flutter/material.dart';
     import 'widgets.dart';

    void main() => runApp(new MaterialApp(
        title: 'Booze Up',
      theme: new ThemeData(
  primarySwatch: Colors.red,
),
home: new MyHomePage('Booze Up'),
routes: <String,WidgetBuilder>
  "/MyHomePage2": (BuildContext context) => new MyHome()

));

       class MyHomePage extends StatelessWidget 

    int counter =0;
    String title;
    MyHomePage(this.title);

     @override
     Widget build(BuildContext context) 


        Text text = new Text("dev");
       Text text2 = new Text("Sneha");
       Text text3 = new Text("Prashant");

var pad = const EdgeInsets.all(10.0);

Padding pad1 = new Padding(child: text, padding:pad);
 Padding pad2 = new Padding(child: text2, padding:pad);
  Padding pad3 = new Padding(child: text3, padding:pad);

     ListView listView = new ListView(children: <Widget>[new 
     Image.asset('images/party.jpg'),pad1,pad2,pad3]);

  Drawer drawer = new Drawer(child:listView); 

// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
  drawer: drawer,
  appBar: new AppBar(
    // Here we take the value from the MyHomePage object that was created by
    // the App.build method, and use it to set our appbar title.
    title: new Text(title),
  ),
  body:
  new Center(

    // Center is a layout widget. It takes a single child and positions it
    // in the middle of the parent.
    child: new Column(
             mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        new Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
              new Icon(Icons.camera),
              new Padding(padding: new EdgeInsets.fromLTRB(0.0,0.0, 5.0,0.0)),
            new RaisedButton(
            color: Colors.black,
          child: 
          new Text(  'Party Home',
          style: new TextStyle(fontSize: 20.0,fontStyle: 
               FontStyle.italic,color: Colors.white),
                   ),
          onPressed: () 
                  Navigator.of(context).pushNamed("/MyHomePage2");
          ,                
       )]),
       new Row(
         mainAxisAlignment: MainAxisAlignment.center,
         children: <Widget>[
         new Icon(Icons.favorite),
        new Padding(padding: new EdgeInsets.fromLTRB(0.0,0.0, 5.0,0.0)),
        new Text(
          'Pub Hopping',
         style: new TextStyle(fontSize: 20.0,fontStyle: FontStyle.italic),

        ),
         ]),
        new Image.asset('images/party.jpg'),   
          ],
        )
        , 
    ),

  floatingActionButton: new FloatingActionButton(
    onPressed: null,
    child: new Icon(Icons.add),
  ), // This trailing comma makes auto-formatting nicer for build methods.
);
   


  

        class MyHome extends StatefulWidget
        
         @override
        State<StatefulWidget> createState() => new MyHomePage2();
         

        class MyHomePage2 extends State<MyHome> 
        List items = new List() ;


        @override
        Widget build(BuildContext context) 

var abc = MediaQuery.of(context).size;

print(abc.width);

var width = abc.width/4;

         Text text = new Text("Dev");
        Text text2 = new Text("Sneha");
        Text text3 = new Text("Prashant");
      Text text4 = new Text("Vikesh");

var pad = const EdgeInsets.all(10.0);

Padding pad1 = new Padding(child: text, padding:pad);
 Padding pad2 = new Padding(child: text2, padding:pad);
  Padding pad3 = new Padding(child: text3, padding:pad);
  Padding pad4 = new Padding(child: text4, padding:pad);

      ListView listView = new ListView(children: <Widget>[new 
      Image.asset('images/party.jpg'),pad1,pad2,pad3,pad4]);


     ListView listView2 = new ListView(children: <Widget>[new Text("Jacob 
        Creek"),new Text("Sula red"),new Text("Yellow tale"),new 
        Text("Chenin Blanc")]);

        Drawer drawer = new Drawer(child: listView);

return new Scaffold(
  drawer: drawer,

  appBar: new AppBar(
    title: new Text('Booze Up'),
  ),
  body:
     new Column(
      children: <Widget>[
        new Row(
           children: <Widget>[
                 new Column(
          children: <Widget>[
                  new FlatButton(child: new 
         Image.asset('images/party.jpg',width:width,height: 
          width),onPressed: buildlist('button1'),),
          new Text('Juice', style: new TextStyle(fontSize: 20.0,fontStyle: 
          FontStyle.italic)),        
          ]),
                new Column(
          children: <Widget>[
        new FlatButton(child: new 
       Image.asset('images/party.jpg',width:width,height: width),onPressed: 
        buildlist('button2')),
          new Text('Cocktail', style: new TextStyle(fontSize: 
         20.0,fontStyle: FontStyle.italic)) ,                     
          ]),
                  new Column(
          children: <Widget>[
      new FlatButton(child: new Image.asset('images/party.jpg',width:width,height: width),onPressed: buildlist('button3')),
          new Text('Moocktail', style: new TextStyle(fontSize: 20.0,fontStyle: FontStyle.italic)),
          ]),
                  new Column(
          children: <Widget>[
     new FlatButton(child: new Image.asset('images/party.jpg',width:width,height: width),onPressed: buildlist('button4')),
          new Text('Juice', style: new TextStyle(fontSize: 20.0,fontStyle: FontStyle.italic)),
          ])
           ]),
        new Expanded(
          child: new ListView(
            padding: new EdgeInsets.fromLTRB(10.0, 10.0, 0.0,10.0),
            children: items,
          ),
        )]
     ),
  floatingActionButton: new FloatingActionButton(
    onPressed: null,
    child: new Icon(Icons.add),
  ), // This trailing comma makes auto-formatting nicer for build methods.
);
            

buildlist(String s ) 

    print("entered buildlist"+ s);

  List refresh = new List();
  if(s=='button1')
  
  refresh = [
   new Refreshments("Watermelon",250),
    new Refreshments("Orange",275),
    new Refreshments("Pine",300),
    new Refreshments("Papaya",225),
     new Refreshments("Apple",250),
];
  
  else if(s=='button2')

     refresh = [
      new Refreshments("Pina Colada",250),
      new Refreshments("Bloody Mary",275),
      new Refreshments("Long Island Ice tea",300),
      new Refreshments("Screwdriver",225),
      new Refreshments("Fusion Cocktail",250),
];
    
    else if(s=='button3')
    
    refresh  = [
       new Refreshments("Virgin Pina Colada",250),
      new Refreshments("Virgin Mary",275),
       new Refreshments("Strawberry Flush",300),
      new Refreshments("Mango Diver",225),
      new Refreshments("Peach Delight",250),
];
    
    else
 refresh = [
       new Refreshments("Absolute",250),
       new Refreshments("Smirnoff",275),
        new Refreshments("White Mischief",300),
        new Refreshments("Romanov",225),
        new Refreshments("Blender's Pride",250),
];
    


 for(var item in refresh)
 
   items.add(new ItemsList(item));
 

  


                 

       class  Refreshments 
 
        String name;
          int price;

           Refreshments(this.name,this.price);
 


            class ItemsList extends StatelessWidget
      
            final Refreshments refreshments;

           ItemsList (this.refreshments);

      @override
        Widget build(BuildContext context) 
     return new ListTile(
      onTap: null,
      title: new Text(refreshments.name),
  );

         
        

【问题讨论】:

【参考方案1】:

    要获得精确的widthheight,请使用Container 作为FlatButton 的父级,它为您提供这些属性。 *Darky 指出使用SizedBox 是更好的解决方案。

    使用ListView 并指定scrollDirection: Axis.horizontal 以启用水平滚动。

    使用ListView.builder 使您能够循环浏览子小部件列表,这样您现在只需读取列表中小部件的索引即可与正在交互的小部件。

示例

import "package:flutter/material.dart";

class LetsParty extends StatefulWidget 
  @override
  _LetsPartyState createState() => new _LetsPartyState();


class _LetsPartyState extends State<LetsParty> 
  Image _partyImage = new Image.network(
      "http://www.freshcardsgifts.co.uk/images/_lib/animal-party-greetings-card-3003237-0-1344698261000.jpg");
  final GlobalKey<ScaffoldState> scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) 
    return new Scaffold(
      key: scaffoldKey,
      appBar: new AppBar(title: new Text("Let's Party"),),
      body: new ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: 10, //add the length of your list here
          itemBuilder: (BuildContext context, int index) 
            return new Column(
              children: <Widget>[

                ///Flexible let's your widget flex in  the given space, dealing with the overflow you have
                //  new Flexible(child: new FlatButton(onPressed: ()=>print("You pressed Image No.$index"), child: _partyImage)),
                new Container(child: new FlatButton(onPressed: () =>
                    scaffoldKey.currentState.showSnackBar(new SnackBar(
                        content: new Text("You pressed Image No.$index"))),
                    child: _partyImage),
                  width: 100.0, height: 100.0,),
                //Exact width and height, consider adding Flexible as a parent to the Container
                new Text("Text$index")
              ],
            );
          ),
    );
  

【讨论】:

使用SizedBox 而不是Container 来调整孩子的大小。这样更清晰,有更多选择。 这是你给的一个非常好的demo。它删除了我的很多冗余代码。但是,buildlist 中的 setState 方法甚至在页面构建之前就被调用了,这是为什么呢?在这个问题中,我忘记了 setState(),后来我将它合并到我的程序中。请你帮忙。 @DivyangShah 很抱歉,我在您的代码中没有看到任何 setState 这就是我后来在发布此问题后包含的内容。主要问题是 buildlist() 甚至在页面加载之前就被调用了。我已将代码包含在 setState 内的 buildlist 中。Like buildlist() setState( () ...code); 这与你在这里问什么无关,也许用相关代码打开另一个问题。

以上是关于调整平面按钮的大小并在颤动中提供水平滚动选项的主要内容,如果未能解决你的问题,请参考以下文章

Java Swing:如何更改 Grid 布局中一行的大小并允许它仅水平而不是垂直地动态调整大小?

颤动中非动态容器小部件的水平轮播

addwidget显示滚动轴

如何调整标签大小以适应任何屏幕尺寸

word 中水平滚动条与垂直滚动条怎样设置与取消??

在颤动的webview中禁用水平滚动