SingleChildScrollView 内的 Column 内的 ListView.builder

Rap*_*uer 1 listview dart flutter

全部。我正在尝试将 a 添加ListView.builder到 aColumn内的 a 中SingleChildScrollView。但是,我遇到了例外,可能是因为ListView.builder. 这是我的代码:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              ListView.builder(
                itemBuilder: (context, index) => const Text('a'),
                itemCount: 2,
              ),
              const Text(
                'You have pushed the button this many times:',
              ),
              Text(
                '$_counter',
                style: Theme.of(context).textTheme.headline4,
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

如果我使用 aContainer并设置定义的高度,上面的代码就可以工作。但是,我试图让其ListView.builder没有固定的大小。我尝试使用该Expanded小部件,但仍然收到此错误。有没有办法在没有定义高度的情况下完成这项工作?谢谢

Kau*_*dru 6

在列小部件中添加mainAxisSize:MainAxisSize.min和 在列表视图.builder 中添加shrinkWrap:truephysics:NeverScrollablePhysics()。这应该可以解决问题,而不是使用中心小部件使用 SafeArea 或具有特定高度的容器。