如何在Flutter中使用容器(Container)和ListView.builder创建一个可滚动的列?

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

How to created a scrollable column with a container and listview builder as child in flutter?

问题

我想创建一个视图,其中会有一个包含一些数据的容器,下面会有一些其他数据的列表。我希望它们两者能够一起滚动。为此,我在SingleChildScrollView内部使用了一个SingleChildScrollView(physics: ScrollPhysics()),在其中我使用了一个Column,而在Column内部,我使用了一个容器和一个ListView.builder(shrinkWrap: true, physics: NeverScrollableScrollPhysics())。但是当我这样做时,我收到了一个异常错误。

**
FlutterError(RenderFlex的子元素具有非零的flex,但传入的高度约束是无界的。
当Column位于不提供有限高度约束的父级中时,例如,如果它位于垂直可滚动区域中,它将尝试沿垂直轴缩小其子元素。在子元素上设置flex(例如使用Expanded)表示子元素将扩展以填充垂直方向的剩余空间。
**

然后,我尝试在builder周围使用Expanded(),我得到了这个错误。

**
FlutterError(RenderFlex的子元素具有非零的flex,但传入的高度约束是无界的。
当Column位于不提供有限高度约束的父级中时,例如,如果它位于垂直可滚动区域中,它将尝试沿垂直轴缩小其子元素。在子元素上设置flex(例如使用Expanded)表示子元素将扩展以填充垂直方向的剩余空间。
**

英文:

I want to make a view where there will be a container with some data and below that a list of some other data. And I want both of them to scroll together. So for that I use a singlechildscrollview (physics: ScrollPhysics(),) inside that I used a column and inside column I used the container and a listview builder(shrinkWrap: true,physics: NeverScrollableScrollPhysics(),). But when did so I got an exception error.

**
FlutterError (RenderFlex children have non-zero flex but incoming height constraints are unbounded.
When a column is in a parent that does not provide a finite height constraint, for example if it is in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining space in the vertical direction.
**

Then I tried the same code after wraping builder with Expended(). I got this error.
**
FlutterError (RenderFlex children have non-zero flex but incoming height constraints are unbounded.
When a column is in a parent that does not provide a finite height constraint, for example if it is in a vertical scrollable, it will try to shrink-wrap its children along the vertical axis. Setting a flex on a child (e.g. using Expanded) indicates that the child is to expand to fill the remaining space in the vertical direction.
**

** MY Code **

import 'package:Healthwise/helpers/dataVariables.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get_navigation/get_navigation.dart';
import '../helpers/backEnd.dart';
import '../helpers/frontEnd.dart';

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

  @override
  State<ResultPage> createState() => _ResultPageState();
}

class _ResultPageState extends State<ResultPage> {
  // String docId = '';
  String objectToString = '';

  // List of string for storing..
  var dataAsString = <String>[];

  @override
  void initState() {
    super.initState();
    // getUsers();
    getUserById();
  }

  getUserById() {
    String id = itemName.toLowerCase().trim();

    fruitInfoDoc.doc(id).get().then((DocumentSnapshot doc) {
      // final x = doc.data();
      // docId= doc.id;
      objectToString = doc.data().toString();
      String temp = '';
      // print(doc.data());
      // print(doc.id);
      int i = 1;

      bool end = false;
      //We are just parsing the object into string.
      while (objectToString[i] != '}') {
        if (objectToString[i - 1] == ' ' && objectToString[i - 2] == ':') {
          while (objectToString[i] != ',' && end != true) {
            temp += objectToString[i];
            if (objectToString[i + 1] != '}') {
              i++;
            } else {
              end = true;
            }
          }
          //Here I add all the strings to list...
          // This line works fine.
          dataAsString.add(temp);
          temp = '';
          print("The code below this line prints everything perfectly");
          print(dataAsString.length);
          print(dataAsString);
        }
        i++;
      }

      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Navigator.pop(context);
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
            automaticallyImplyLeading: false,
            backgroundColor: primary_color,
            title: Center(
              child: Text(
                itemName.trim().toUpperCase(),
                style: TextStyle(
                    //Fruit Name
                    color: Color.fromARGB(255, 255, 255, 255),
                    fontSize: 15),
              ),
            )),
        body: SingleChildScrollView(
          physics: ScrollPhysics(),
          child: Column(
            children: [
              Container(
                color: Color.fromARGB(255, 150, 50, 50),
                height: 200,
                width: 100,
              ),
              Expanded(
                child: Expanded(
                  child: Builder(
                    builder: (context) {
                      if (dataAsString.length > 0) {
                        return ListView.builder(
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            itemCount: dataAsString.length,
                            itemBuilder: (BuildContext context, int index) {
                              return EditedListTile(
                                dataAsString: dataAsString,
                                index: index,
                              );
                            });
                      } else {
                        return const Center(
                          child: CircularProgressIndicator(),
                        );
                      }
                    },
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

答案1

得分: 1

以下是翻译好的部分:

"Since I couldn't use your code to debug, here is something similar to what you're trying to do. You were getting that error because you didn't have your Expanded widgets in the correct place.

You have your entire page scrollable with a container inside that has a scrollable ListView or remove ListView and add another widget in its place.

Below that, you have another widget with a scrollable ListView. You can replace that with another widget but keep the Expanded widget as it is."

英文:

Since I couldn't use your code to debug, here is something similar to what you're trying to do. You were getting that error because you didn't have your Expanded widgets in correct place.

You have you're entire page scrollable with container inside that has scrollable Listview or remove Listview and add other widget at is place.

Below that you have another widget scrollable Listview, you can replace that with other widget and but keep Expanded widget as it is.

For more info on Expanded Widget

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

  @override
  State<ResultPage> createState() => _ResultPageState();
}

class _ResultPageState extends State<ResultPage> {
  // String docId = '';
  String objectToString = '';

  // List of string for storing..
  List<String> list = List<String>.generate(100, (counter) => "Item $counter");

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Navigator.pop(context);
        return false;
      },
      child: Scaffold(
        appBar: AppBar(
          automaticallyImplyLeading: false,
          title: Center(
            child: Text(
              'itemName'.trim().toUpperCase(),
              style: TextStyle(
                  //Fruit Name
                  color: Color.fromARGB(255, 255, 255, 255),
                  fontSize: 15),
            ),
          ),
        ),
        body: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height * 1,
            child: Column(
              children: [
                Expanded(
                  child: Container(
                    color: Color.fromARGB(255, 150, 50, 50),
                    width: 100,
                    child: ListView.builder(
//                   physics: NeverScrollableScrollPhysics(), // Uncomment this to stop scroll
                      itemCount: list.length,
                      itemBuilder: (BuildContext context, int index) {
                        return Text(list[index]);
                      },
                    ),
                  ),
                ),
                Expanded(
                  child: ListView.builder(
//                   physics: NeverScrollableScrollPhysics(), // Uncomment this to stop scroll
                    itemCount: list.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Text(list[index]);
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

huangapple
  • 本文由 发表于 2023年2月19日 09:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497440.html
匿名

发表评论

匿名网友

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

确定