Как указать ширину элементов в развернутом списке Flutter? - PullRequest
1 голос
/ 07 мая 2020

Приведенный ниже код представляет собой список элементов, в котором список должен быть полной ширины, но элементы внутри списка могут отсутствовать. Кажется, Flutter игнорирует мое ограничение ширины SizedBox и заставляет его полностью расширяться.

class ExampleBadListWidth extends StatelessWidget {
  List<String> things = [
    "1: This is a really really really really really really really  really really really  long thing",
    "2: This is a really really really really really really really  really really really  long thing",
    "3: This is a really really really really really really really  really really really  long thing"
  ];

  ExampleBadListWidth();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(children: [
      Expanded(
          child: ListView.builder(
        itemCount: things.length,
        itemBuilder: _thingBuilder,
      ))
    ]));
  }

  Widget _thingBuilder(context, index) {
    return SizedBox(width: 100, child: Text(things[index]));
  }
}

1 Ответ

2 голосов
/ 07 мая 2020

Вы можете скопировать и вставить полный код ниже
Вы можете заключить SizedBox в Center или Align

фрагмент кода

Widget _thingBuilder(context, index) {
    return Center(
      child: SizedBox(
          width: 100,
          child: Text(things[index])),
    );
  }

или

 Widget _thingBuilder(context, index) {
    return Align(
      alignment: Alignment.centerLeft,
      child: SizedBox(
          width: 100,
          child: Text(things[index])),
    );
  }  

рабочая демонстрация

enter image description here

полный код

import 'package:flutter/material.dart';

class ExampleBadListWidth extends StatelessWidget {
  List<String> things = [
    "1: This is a really really really really really really really  really really really  long thing",
    "2: This is a really really really really really really really  really really really  long thing",
    "3: This is a really really really really really really really  really really really  long thing"
  ];

  ExampleBadListWidth();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(children: [
      Expanded(
          child: ListView.builder(
        itemCount: things.length,
        itemBuilder: _thingBuilder,
      ))
    ]));
  }

  Widget _thingBuilder(context, index) {
    return Align(
      alignment: Alignment.centerLeft,
      child: SizedBox(
          width: 100,
          child: Text(things[index])),
    );
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ExampleBadListWidth(),
    );
  }
}
...