Home > database >  How do I move the list to the center of the screen?
How do I move the list to the center of the screen?

Time:07-04

I'm going through the first codelab for flutter. I have no experience with coding and am new to flutter. I'm trying to play around with modifying the given code but everything I type returns a million errors. How do I adjust the positioning of the infinite scroll list?

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Name generator',
      home: Scaffold(
        appBar: AppBar(
          title: const Text('name generator'),
        ),
        body: const Center(
          child: RandomWords(),
        ),
      ),
    );
  }
}

class RandomWords extends StatefulWidget {
  const RandomWords({Key? key}) : super(key: key);

  @override
  State<RandomWords> createState() => _RandomWordsState();
}

class _RandomWordsState extends State<RandomWords> {
  final _suggestions = <WordPair>[];
  final _biggerFont = const TextStyle(fontSize: 18);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: const EdgeInsets.all(16.0),
      itemBuilder: (context, i) {
        if (i.isOdd) return const Divider();

        final index = i ~/ 2;
        if (index >= _suggestions.length) {
          _suggestions.addAll(generateWordPairs().take(10));
        }
        return ListTile(
          title: Text(
            _suggestions[index].asPascalCase,
            style: _biggerFont
          ),
        );
      },
    );
  }
}

I figured the way was to add body: const Center( right above the padding for the list but it didn't work, and I don't know where to put it.

Mock up of centering text

CodePudding user response:

You can wrap your Text to make it center.

return ListTile(
  title: Center(
    child: Text(_suggestions[index].asPascalCase, style: _biggerFont),
  ),
);

CodePudding user response:

 return ListTile(
          title: Text(
            _suggestions[index].asPascalCase,
            style: _biggerFont,
           textAlign: TextAlign.center,
          ),
        );

CodePudding user response:

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.

CodePudding user response:

your ListTile widget takes a full-screen width widget so you can directly align text to the center in Text Widget.

return ListTile(
      title: Text(
        _suggestions[index].asPascalCase,
        style: _biggerFont,
       textAlign: TextAlign.center,
      ),
    );
  • Related