如何创建一个占用所有可用空间的可滚动列表?

huangapple go评论60阅读模式
英文:

How can I create a scrollable list that takes all available space?

问题

以下是已翻译的部分代码:

我尝试创建一个可滚动的列表,它会自动扩展以占用可用空间。

以下是我的实际代码,它可以工作,但指定了固定高度为610

import 'package:flutter/material.dart';

class MyWidget extends StatelessWidget {
  final List<String> _myTable;

  const MyWidget(this._myTable);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Stackoverflow示例'),
      ),
      body: Container(
        color: const Color.fromRGBO(33, 33, 33, 0.2),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                height: 610,
                color: const Color.fromRGBO(33, 33, 33, 0.2),
                child: _myTable.isEmpty
                    ? const Center(
                        child: Text('加载表格...'),
                      )
                    : ListView.builder(
                        itemBuilder: (ctx, index) {
                          return Text(_myTable[index]);
                        },
                        itemCount: _myTable.length,
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

如果删除 height: 610, 这一行,您将收到以下错误:

以下是错误信息的一部分:

"The following RenderObject was being processed when the exception was fired: RenderViewport#827e1 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE..."

您的想法是,如果我创建一个具有固定高度610的列表,如果将其移至另一台设备,可能会崩溃或显示不正常... 那么如何使可滚动列表占用所有可用高度呢?

英文:

I'm trying to make a scrollable list that automatically expands taking the available space.

Here is my actual code which is working but specifying a fixed height of 610:

import &#39;package:flutter/material.dart&#39;;

class MyWidget extends StatelessWidget {
  final List&lt;String&gt; _myTable;

  const MyWidget(this._myTable);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(&#39;Stackoverflow example&#39;),
      ),
      body: Container(
        color: const Color.fromRGBO(33, 33, 33, 0.2),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                height: 610,
                color: const Color.fromRGBO(33, 33, 33, 0.2),
                child: _myTable.isEmpty
                    ? const Center(
                        child: Text(&#39;Loading table...&#39;),
                      )
                    : ListView.builder(
                        itemBuilder: (ctx, index) {
                          return Text(_myTable[index]);
                        },
                        itemCount: _myTable.length,
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

If I remove that height: 610, line I will get the following error:

The following RenderObject was being processed when the exception was fired: RenderViewport#827e1 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
RenderObject: RenderViewport#827e1 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    needs compositing
    parentData: &lt;none&gt; (can use size)
    constraints: BoxConstraints(w=411.4, 0.0&lt;=h&lt;=Infinity)
    size: MISSING
    axisDirection: down
    crossAxisDirection: right
    offset: ScrollPositionWithSingleContext#2ab34(offset: 0.0, range: null..null, viewport: null, ScrollableState, AlwaysScrollableScrollPhysics -&gt; ClampingScrollPhysics -&gt; RangeMaintainingScrollPhysics, IdleScrollActivity#6a07b, ScrollDirection.idle)
    anchor: 0.0
    center child: RenderSliverPadding#4985e NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
        parentData: paintOffset=Offset(0.0, 0.0)
        constraints: MISSING
        geometry: null
        padding: EdgeInsets.zero
        textDirection: ltr
        child: RenderSliverList#33a39 NEEDS-LAYOUT NEEDS-PAINT
            parentData: paintOffset=Offset(0.0, 0.0)
            constraints: MISSING
            geometry: null
            no children current live
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderViewport#827e1 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
&#39;package:flutter/src/rendering/box.dart&#39;:
box.dart:1
Failed assertion: line 2009 pos 12: &#39;hasSize&#39;

The relevant error-causing widget was
ListView

And that error is pointing to this line of my code:

: ListView.builder(

My idea is that if I create a list with a fixed height of 610 if I move it to another device it will crash or look bad... so how can I make the scrollable list to take all available height?

答案1

得分: 1

以下是代码的翻译部分:

考虑使用CustomScrollView,它可以帮助您解决问题,查看下面的代码

main.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 const MaterialApp(
      title: "My App",
      home: HomePage(),
    );
  }
}

class HomePage extends StatelessWidget {

  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            title: const Text("My super App")
          ),
          SliverToBoxAdapter(
            child: Container(
              alignment: Alignment.center,
              height: 100,
              color: Colors.redAccent,
              child: Text("Header view"),
            ),
          ),
          SliverList(delegate: SliverChildListDelegate(
            List.generate(20, (idx) {
                return Padding(
                  padding: const EdgeInsets.all(10),
                  child: Card(
                    child: ListTile(
                      leading: const Icon(Icons.check_circle),
                      title: Text("Item $idx"),
                    ),
                  ),
                );
              })
            ),
          ),
        ],
      ),
    );
  }
}

希望这能帮助您理解代码的内容。如果有其他问题,请随时提出。

英文:

Think about using the CustomScrollView which can help you solve your problem, see the code below

main.dart

import &#39;package:flutter/material.dart&#39;;


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

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

  @override
	Widget build(BuildContext context) {
		return const MaterialApp(
			title: &quot;My App&quot;,
			home: HomePage(),
		);
	}
}

class HomePage extends StatelessWidget {
  
  const HomePage({super.key});
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [
          SliverAppBar(
            title: const Text(&quot;My super App&quot;)
          ),
          SliverToBoxAdapter(
            child: Container(
              alignment: Alignment.center,
              height: 100,
              color: Colors.redAccent,
              child: Text(&quot;Header view&quot;),
            ),
          ),
          SliverList(delegate: SliverChildListDelegate(
            List.generate(20, (idx) {
                return Padding(
                  padding: const EdgeInsets.all(10),
                  child: Card(
                    child: ListTile(
                      leading: const Icon(Icons.check_circle),
                      title: Text(&quot;Item $idx&quot;),
                    ),
                  ),
                );
              })
      			),
      		),
       	],
      ),
    );
  }
}

huangapple
  • 本文由 发表于 2023年4月10日 20:00:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定