BoxConstraints 强制无限宽度(列中的列表视图)

问题描述 投票:0回答:1

在列中添加列表视图生成器时出现错误。 我收到以下错误:

这是我的任务小部件页面:

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:gridview/Views/data/firestore_tasks.dart';
import '../Models/Task.dart';
import '../Views/HomeScreens/edit_task.dart';
import '../const/colors.dart';
import 'package:intl/intl.dart';

class Task_wdgts extends StatefulWidget {
  final Task _task;
  Task_wdgts(this._task, {super.key});

  @override
  State<Task_wdgts> createState() => _Task_wdgtsState();
}

class _Task_wdgtsState extends State<Task_wdgts> {
  late bool isDon;
  late Timestamp? newTimeDate;

  @override
  void initState() {
    super.initState();
    isDon = widget._task.isDone;
    newTimeDate = widget._task.time;
  }

  String formattedDatee(Timestamp? timestamp) {
    if (timestamp == null) {
      return 'No date';
    }
    DateTime dateTime = timestamp.toDate();
    return DateFormat('dd-MM-yyyy hh:mm a').format(dateTime);
  }

  @override
  Widget build(BuildContext context) {
    // bool isDon = widget._task.isDone;

    // DateTime dateTime = DateTime.now();

    return Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: 30.0,
        vertical: 5.0,
      ),
      child: Container(
        width: MediaQuery.of(context).size.width, //Set width based on screen width
        decoration: BoxDecoration(
            color: secondaryColor, borderRadius: BorderRadius.circular(15)),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.only(right: 25.0),
              child: imagee(),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // SizedBox(
                  //   height: 25,
                  // ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ListTile(
                        title: Text(
                          widget._task.title,
                          style: const TextStyle(
                              color: textColor,
                              fontSize: 18.0,
                              fontWeight: FontWeight.w700,
                              letterSpacing: 1.0),
                        ),

                        // SizedBox(width: 130.0),
                        trailing: Checkbox(
                          activeColor: secondaryColor,
                          value: isDon,
                          onChanged: (value) {
                            setState(() {
                              isDon = value ?? false;
                            });
                            FirestoreDataSource()
                                .markAsDone(widget._task.id, isDon);
                          },
                        ),
                      ),
                    ],
                  ),
                  // const SizedBox(height: 5),
                  Text(widget._task.subtitle,
                      style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 14.0,
                          fontWeight: FontWeight.w700,
                          letterSpacing: 1.0)),
                  const SizedBox(
                    height: 9.0,
                  ),
                  Row(
                    children: [
                      // EDIT DATE & TIME
                      GestureDetector(
                        onTap: () async {
                          DateTime? newDate = await showDatePicker(
                            context: context,
                            initialDate: newTimeDate?.toDate() ??
                                DateTime.now(), // Convert Timestamp to DateTime
                            firstDate: DateTime(2020),
                            lastDate: DateTime(2030),
                          );

                          TimeOfDay? newTime = await showTimePicker(
                            context: context,
                            initialTime: TimeOfDay.fromDateTime(
                              newTimeDate?.toDate() ?? DateTime.now(),
                            ), // -----------------
                          );
                          if (newTime == null) return;

                          final newDateTime = DateTime(
                            newDate!.year,
                            newDate.month,
                            newDate.day,
                            newTime.hour,
                            newTime.minute,
                          );

                          setState(() {
                            newTimeDate = Timestamp.fromDate(newDateTime);
                            FirestoreDataSource()
                                .editTimeDate(widget._task.id, newTimeDate!);
                          });
                        },
                        child: Container(
                          width: 90,
                          height: 28,
                          decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(18),
                          ),
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 6,
                            ),
                            child: Row(
                              children: [
                                const Icon(
                                  Icons.timer,
                                  color: textColor,
                                  size: 18.0,
                                ),
                                const SizedBox(width: 10),
                                Text(
                                  formattedDatee(newTimeDate),
                                  style: const TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),

                      const SizedBox(
                        width: 20.0,
                      ),
                      // EDIT TASK
                      GestureDetector(
                        onTap: () {
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (context) =>
                                  Edit_task_Screen(widget._task),
                            ),
                          );
                        },
                        child: Container(
                          width: 90,
                          height: 28,
                          decoration: BoxDecoration(
                            color: primaryColor,
                            borderRadius: BorderRadius.circular(18),
                          ),
                          child: const Padding(
                            padding: EdgeInsets.symmetric(
                              horizontal: 12,
                              vertical: 6,
                            ),
                            child: Row(children: [
                              Icon(
                                Icons.edit,
                                color: textColor,
                                size: 18.0,
                              ),
                              SizedBox(width: 10),
                              Text('Edit',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                  ))
                            ]),
                          ),
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
            // Spacer(),
          ],
        ),
      ),
    );
  }

  Widget imagee() {
    return Container(
      height: 110,
      width: 70,
      decoration: BoxDecoration(
          borderRadius: const BorderRadius.only(
              topLeft: Radius.circular(15.0),
              bottomLeft: Radius.circular(15.0)),
          color: textColor,
          image: DecorationImage(
              image: AssetImage(
                'img/${widget._task.image}.png',
              ),
              fit: BoxFit.contain)),
    );
  }
}

这是我的直播页面:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:gridview/Models/Task.dart';
import 'package:gridview/Views/data/firestore_tasks.dart';
import 'package:gridview/widgets/task_widgets.dart';

import '../const/colors.dart';

class stream extends StatefulWidget {
  stream({super.key});

  @override
  State<stream> createState() => _streamState();
}

class _streamState extends State<stream> {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<User?>(
      stream: FirebaseAuth.instance.authStateChanges(),
      builder: (context, userSnapshot) {
        if (userSnapshot.connectionState == ConnectionState.waiting) {
          return const CircularProgressIndicator();
        }

        final User? currentUser = userSnapshot.data;

        return StreamBuilder<List<Task>>(
          stream: FirestoreDataSource().streamTasks(currentUser?.uid ?? ''),
          builder: (context, tasksSnapshot) {
            if (tasksSnapshot.connectionState == ConnectionState.waiting) {
              return const Center(
                child: CircularProgressIndicator(strokeWidth: 0.9),
              );
            }

            if (tasksSnapshot.hasError) {
              print('Error fetching tasks: ${tasksSnapshot.error}');
              return const Center(
                child: Text(
                  'Error fetching tasks.',
                  style: TextStyle(fontSize: 16, color: textColor),
                ),
              );
            }

            final List<Task>? tasksList = tasksSnapshot.data;

            if (tasksList == null) {
              print('Tasks list is null.');
              return const Center(
                child: Text(
                  'No tasks available (null).',
                  style: TextStyle(fontSize: 16, color: textColor),
                ),
              );
            }

            if (tasksList.isEmpty) {
              print('Tasks list is empty.');
              return const Center(
                child: Text(
                  'No tasks available (empty).',
                  style: TextStyle(fontSize: 16, color: textColor),
                ),
              );
            }

            return Column(
              children: [
                Expanded(
                  child: ListView.builder(
                    physics: ClampingScrollPhysics(),
                    shrinkWrap: true,
                    itemCount: tasksList.length,
                    itemBuilder: (context, index) {
                      final task = tasksList[index];
                      return Dismissible(
                        key: UniqueKey(),
                        onDismissed: ((direction) {
                          FirestoreDataSource().deleteTask(task.id);
                        }),
                        child: Task_wdgts(task),
                      );
                    },
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }
}

我的主页:

import 'package:flutter/material.dart';
import 'package:gridview/widgets/stream.dart';
import 'package:gridview/widgets/whatsapp_widget.dart';

class Home extends StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool show = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: whatsapp(),
          ),
          Expanded(
            child: stream(),
          ),
        ],
      ),
    );
  }
}

我尝试了解决方案:

class Home extends StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool show = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: Container(
              width: double.infinity, // or specify a fixed width
              child: stream(),
            ),
          ),
        ],
      ),
    );
  }
}

class Home extends StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  bool show = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(child: stream()), // Ensure stream widget is wrapped with Expanded
        ],
      ),
    );
  }
}

class _HomeState extends State<Home> {
  bool show = true;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height,
      child: stream(),
    );
  }
}

class _HomeState extends State<Home> {
  bool show = true;

  @override
  Widget build(BuildContext context) {
    return stream();
  }
}

class _HomeState extends State<Home> {
  bool show = true;

  @override
  Widget build(BuildContext context) {
    return Flexible(
      child: stream(),
    );
  }
}

我知道这太长了,我已经被这个问题折磨了三天多了,所以我尝试把所有的代码都贴出来。你可以看看我的解决方案。也许我忽略了一些事情。 预先感谢。

flutter dart listview android-listview flutter-column
1个回答
0
投票

在您的

Task_wdgts
类中,
ListTile
小部件的直接父级是 Row,这似乎导致了问题。您也不需要 Row 小部件,因为您只显示单个子小部件,即
Row

尝试删除 Row 小部件,它应该可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.