Enzo Saoud
Enzo Saoud

Reputation: 49

Center ListView

I would like to know how can i make 2 itens in a ListView centered in the screen.

class _CategoriesState extends State<Categories> {
  List<String> categories = ["Anteriores", "Ativos"];

  int selectedIndex = 0;
  final List pages = [
    Busca(),
    Perfil(),
  ];


  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20),
      child: SizedBox(
        height: 25,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: categories.length,
          itemBuilder: (context, index) => buildCategory(index),
        ),
      ),
    );
  }


 

Here's a picture how it looks like : http://prntscr.com/triyly

Ps: This is not the full code for the ListView as stackOverflow does says i am putting too many code and just a few words.

Upvotes: 0

Views: 365

Answers (3)

HBS
HBS

Reputation: 670

You can use Align as well:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20),
      child: Container(
        height: 250,
        color: Colors.green,
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: 2,
          itemBuilder: (context, index) => Align(
            alignment: Alignment.center,
            child: Row(
              children: [
                Text("1"),
                Text("2"),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Upvotes: 0

Navaneeth P
Navaneeth P

Reputation: 1561

You can just set shrinkWrap to true and wrap the ListView with Center.

Center(
  child: ListView.builder(
    shrinkWrap: true,
    ...
  )
),

Upvotes: 1

HasilT
HasilT

Reputation: 2609

Wrap your ListView inside a Row widget and give mainAxisAlignment for the Row to the center.

SizedBox(
          height: 65,
          child:
              Row(
                mainAxisAlignment: MainAxisAlignment.center, // to align center
              children: [
            ListView.builder(
              scrollDirection: Axis.horizontal,
              shrinkWrap: true,
              itemCount: 3,
              itemBuilder: (context, index) => Container(
                  color: Colors.blue,
                  height: 150,
                  width: 60,
                  margin: EdgeInsets.all(10),
                  child: Text('$index')),
            ),
          ]))

Upvotes: 0

Related Questions