简体   繁体   中英

How to center the Title of a ListTile in Flutter

I have been trying again today to center the title of a Flutter ListTile. Over the past few days I have spent an hour or two Googling and trying things then loosing my cool and giving up.

I am just learning Flutter and love the concept but can find no video training courses (Lynda.com, uDemy.com etc). I have read through the relevant documentation but cannot get rid of all the red lines that appear when I try to apply them to my code.

There must be logic in the syntax but after 2 weeks I have not worked it out yet.

Back to the problem, I have tried

List<Widget> list = <Widget>[
  new ListTile(
    new child: Center (
      title:
          new Text('Title 1',
            style: new TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.deepOrangeAccent,
                fontSize: 25.0)),
    )
  ),
];


List<Widget> list = <Widget>[
  new ListTile(
    title:
            new child: Center (
          new Text('Title 2',
            style: new TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.deepOrangeAccent,
                fontSize: 25.0)),
    )
  ),
];


List<Widget> list = <Widget>[
  new ListTile(
    child: Center 
            title: (
                new Text('Title 3',
                    style: new TextStyle(
                            fontWeight: FontWeight.w500,
                            color: Colors.deepOrangeAccent,
                fontSize: 25.0)),
    )
  ),
];


List<Widget> list = <Widget>[
  new ListTile(
        title: Center
                new Text('Title 4',
                    style: new TextStyle(
                            fontWeight: FontWeight.w500,
                            color: Colors.deepOrangeAccent,
                            fontSize: 25.0)),
    )
  ),
];

Please help me with this problem and also where to find a video course on Flutter?

On the upside, if this continues I will no longer be grey, I will be bald instead.

I thought I worked it out when I added 'textAlign: TextAlign.center,' to the text object. There were no red lines but the text was still left aligned.

I am not sure what have you tried, but you in order to center the title of the ListTile you can use a center widget like you did in your code, or wrap your text within a Row widget and set mainAxisAlignment: MainAxisAlignment.center .

Using Center widget:

@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text("ListTile Example"),),
      body: new ListView(
        children: new List.generate(7, (int index) {
          return new ListTile(
            title: new Center(child: new Text("Centered Title#$index",
              style: new TextStyle(
                  fontWeight: FontWeight.w500, fontSize: 25.0),)),
            subtitle: new Text("My title is centered"),
          );
        }),
      ),
    );
  }

Using Row widget:

 @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text("ListTile Example"),),
      body: new ListView(
        children: new List.generate(7, (int index) {
          return new ListTile(
            title: new Row(children: <Widget>[new Text("Centered Title#$index",
              style: new TextStyle(
                  fontWeight: FontWeight.w500, fontSize: 25.0),)
            ], mainAxisAlignment: MainAxisAlignment.center,),
            subtitle: new Text("My title is centered"),
          );
        }),
      ),
    );
  }

However, your problem is not about centering the title, it is about you are trying to insert too big of a Text inside a small area, that is why you are getting the red lines, so one solution is choose a smaller fontSize , a better solution is to get rid of ListTile and build your own custom widget, since a ListTile is

A single fixed-height row that typically contains some text as well as a leading or trailing icon.

So it should not be used if you are using bigger widgets.

This is simple example of how to create a custom widget that resembles ListTile , but is more flexible and customizable when dealing with larger items:

@override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(title: new Text("ListTile Example"),),
        body: new ListView(
          children: new List.generate(7, (int index) {
            return new Container(
              padding: const EdgeInsets.symmetric(
                  vertical: 10.0, horizontal: 20.0),
              child: new Column(
                children: <Widget>[
                  new Align (child: new Text("Centered Title $index",
                    style: new TextStyle(fontSize: 40.0),), //so big text
                    alignment: FractionalOffset.topLeft,),
                  new Divider(color: Colors.blue,),
                  new Align (child: new Text("Subtitle $index"),
                    alignment: FractionalOffset.topLeft,),
                  new Divider(color: Colors.blue,),
                  new Align (child: new Text("More stuff $index"),
                    alignment: FractionalOffset.topLeft,),
                  new Row(mainAxisAlignment: MainAxisAlignment.end,
                    children: <Widget>[ //add some actions, icons...etc
                      new FlatButton(onPressed: () {}, child: new Text("EDIT")), 
                      new FlatButton(onPressed: () {},
                          child: new Text("DELETE",
                            style: new TextStyle(color: Colors.redAccent),))
                    ],),
                ],
              ),
            );
          }),
        )
    );
  }

在此输入图像描述

Here is my example of a three-row tile:

   class ThreeRowTile extends StatelessWidget {
      final Widget title;
      final Widget detail;
      final String utility1;
      final String utility1Help;
      final String utility2Help;
      final String utility2;
      final Icon icon;
      final String cell;
      final String home;
      final String office;
      final String email;
      final VoidCallback cellTapped;
      final VoidCallback cellLongPressed;
      final VoidCallback iconTapped;

      ThreeRowTile({
        this.title,
        this.icon,
        this.detail,
        this.utility1,
        this.utility1Help,
        this.utility2,
        this.utility2Help,
        this.cellTapped,
        this.home,
        this.email,
        this.cell,
        this.office,
        this.cellLongPressed,
        this.iconTapped,
      });

      @override
      Widget build(BuildContext context) {
        List<Widget> buildChildren() {
          List<Widget> builder = [];
          if (cell.isNotEmpty && !cell.toString().contains("--")) {
            builder.add(ListTile(
              leading: const Icon(Icons.phone),
              title: Text(
                'Cell',
                textScaleFactor: globals.textScaleFactor,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              subtitle: Text(
                cell.toString().length > 0 ? cell : "No Number Found",
                textScaleFactor: globals.textScaleFactor,
              ),
              onTap: cell.toString().contains("--")
                  ? null
                  : () {
                      globals.Utility.makePhoneCall(context, cell);
                    },
            ));
          }

          if (office.isNotEmpty && !office.toString().contains("--")) {
            builder.add(ListTile(
              leading: const Icon(Icons.work),
              title: Text(
                'Office',
                textScaleFactor: globals.textScaleFactor,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              subtitle: Text(
                office.toString().length > 0 ? office : "No Number Found",
                textScaleFactor: globals.textScaleFactor,
              ),
              onTap: office.toString().contains("--")
                  ? null
                  : () {
                      globals.Utility.makePhoneCall(context, office);
                    },
            ));
          }
          if (home.isNotEmpty && !home.toString().contains("--")) {
            builder.add(ListTile(
              leading: const Icon(Icons.home),
              title: Text(
                'Home',
                textScaleFactor: globals.textScaleFactor,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              subtitle: Text(
                home.toString().length > 0 ? home : "No Number Found",
                textScaleFactor: globals.textScaleFactor,
              ),
              onTap: home.toString().contains("--")
                  ? null
                  : () {
                      globals.Utility.makePhoneCall(context, home);
                    },
            ));
          }
          if (email.isNotEmpty && !email.contains('No Email Address')) {
            builder.add(ListTile(
              leading: const Icon(Icons.email),
              title: Text(
                'Email',
                textScaleFactor: globals.textScaleFactor,
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                ),
              ),
              subtitle: Text(
                email.toString().length > 0 ? email : "No Email Found",
                textScaleFactor: globals.textScaleFactor,
              ),
              onTap: email.toString().isEmpty
                  ? null
                  : () {
                      globals.Utility.sendEmail(context, email);
                    },
            ));
          }
          if (builder.isEmpty) {
            builder.add(
              ListTile(
                leading: const Icon(Icons.info),
                title: Text(
                  'No Contact Information Found',
                  textScaleFactor: globals.textScaleFactor,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            );
          }
          return builder;
        }

        String _utility1 =
            utility1 == null || utility1.contains("1-1-1800") ? "" : utility1;
        String _utility2 =
            utility2 == null || utility2.contains("1-1-1800") ? "" : utility2;

        var rowCard = Container(
          decoration: BoxDecoration(
              border: Border(bottom: BorderSide(color: Colors.grey[300]))),
          child: Container(
            padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 5.0),
            child: new Column(
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Align(
                      child: IconButton(
                        icon: icon,
                        onPressed: iconTapped,
                      ),
                      alignment: FractionalOffset.centerLeft,
                    ),
                    Expanded(
                      child: Column(
                        children: <Widget>[
                          new Align(
                            child: title, //so big text
                            alignment: FractionalOffset.topLeft,
                          ),
                          // new Divider(),
                          new Align(
                            child: detail,
                            alignment: FractionalOffset.topLeft,
                          ),
                          // new Divider(),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              Expanded(
                                child: Container(
                                  margin: const EdgeInsets.all(3.0),
                                  padding: const EdgeInsets.all(3.0),
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                          color: _utility1.length > 1
                                              ? Colors.grey
                                              : Colors.transparent)),
                                  child: Tooltip(
                                    message:
                                        utility1Help == null ? "" : utility1Help,
                                    child: Text(
                                      _utility1,
                                      maxLines: 1,
                                      textAlign: TextAlign.center,
                                      textScaleFactor: globals.textScaleFactor,
                                    ),
                                  ),
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  margin: const EdgeInsets.all(3.0),
                                  padding: const EdgeInsets.all(3.0),
                                  decoration: BoxDecoration(
                                      border: Border.all(
                                          color: _utility2.length > 1
                                              ? Colors.grey
                                              : Colors.transparent)),
                                  child: Tooltip(
                                    message: utility2 == null ? "" : utility2,
                                    child: Text(
                                      _utility2,
                                      maxLines: 1,
                                      textAlign: TextAlign.center,
                                      textScaleFactor: globals.textScaleFactor,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                    Align(
                      child: IconButton(
                        icon: Icon(Icons.arrow_drop_down),
                        onPressed: () {
                          showModalBottomSheet<void>(
                              context: context,
                              builder: (BuildContext context) {
                                return Container(
                                    child: Padding(
                                  padding: EdgeInsets.only(bottom: 10.0),
                                  child: SingleChildScrollView(
                                    child: Column(
                                        mainAxisSize: MainAxisSize.min,
                                        children: buildChildren()),
                                  ),
                                ));
                              });
                        },
                      ),
                      alignment: FractionalOffset.centerRight,
                    ),
                  ],
                ),
              ],
            ),
          ),
          // color: globals.isDarkTheme ? Colors.black45 : Colors.white,
        );

        return (rowCard);
      }
    }

And it can be used like this:

ThreeRowTile(
      icon: Icon(Icons.person),
      title: _contacts?.items[index]?.lastName.toString().isEmpty &&
              _contacts?.items[index]?.firstName.toString().isEmpty
          ? null
          : Text(
              (_contacts?.items[index]?.lastName ?? "") +
                  ", " +
                  (_contacts?.items[index]?.firstName ?? ""),
              textScaleFactor: globals.textScaleFactor,
            ),
      detail: Text(
        _contacts?.items[index]?.lastActivity,
        textScaleFactor: globals.textScaleFactor,
      ),
      utility1: _contacts?.items[index]?.dateCreated,
      utility1Help: 'Date Created',
      utility2: _contacts?.items[index]?.dateModified,
      utility2Help: "Date Modified",
      cell: _contacts?.items[index]?.cell,
      home: _contacts?.items[index]?.home,
      office: _contacts?.items[index]?.office,
      email: _contacts?.items[index]?.email,
      cellTapped: () {
        globals.contactID = _contacts?.items[index]?.contactID;
        Navigator.of(context).pushNamed("/contact_details").then((value) {
          if (globals.infoChanged) {
            _getData("", false).then((newitems) {
              setState(() {
                _contacts = newitems;
              });
            });
          }
        });
      },
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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