BoxConstraints forces an infinite width (listview in a Column)

51 views Asked by At

I am getting an error when I add the listview builder in the column. I am getting the following error: error message

this is my task widget page:

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)),
    );
  }
}

And here is my stream page:

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),
                      );
                    },
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }
}

My home page:

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(),
          ),
        ],
      ),
    );
  }
}

I tried the solutions:

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(),
    );
  }
}

I know this is too long, I have been miserable with this problem for more than three days, so I tried to put all the code. You can see the solution for me. Maybe I overlooked something. Thanks in advance.

1

There are 1 answers

0
Calvin Gonsalves On BEST ANSWER

In your Task_wdgts class the immediate parent of the ListTile widget is a Row and this seems to be causing the problem. You also do not need a Row widget as you only are displaying a single child widget i.e Row.

Try removing the Row widget and it should work.