简体   繁体   中英

why space is leaving while adding widgets inside Wrap widget in flutter?

I have created a custom widget which is an entirely separate class so while pressing an add more button the custom widget should be added inside Wrap Widget, everything working fine but while adding a custom widget inside the Wrap widget it leaves space on the right side and custom widgets are adding next row. Below I have attached a screenshot where we can see the space a lot of space. I don't want to leave space like below can anyone help in this case. Thanks in advance.

在此处输入图像描述

this is my code

import 'package:flutter/cupertino.dart';
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(),
    );
  }
}

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


  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int count =0;
  List images = [];

  void onCrossSelected(UniqueKey id) {
setState(() {
  print("${id.hashCode}");
  images.removeWhere((element) => element.id.hashCode == id.hashCode);
});
  }
  void addAtInitial() {
    setState(() {
      images.add(ItemButton(
        onCrossSelect: (UniqueKey sId) {
        onCrossSelected(sId);
      },
          id: UniqueKey(),
        initialItem: 0,
      ));
    });
  }

  @override
  void initState() {
    addAtInitial();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SingleChildScrollView(
              child: Wrap(
                children: [
                  ...images,
                  Padding(padding: const EdgeInsets.all(8.0),
                  child: Container(
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          images.add(ItemButton(onCrossSelect: (UniqueKey sId) {
                            onCrossSelected(sId);
                          }, id: UniqueKey()));
                        });
                      },
                      child: Column(
                        children: [
                          Container(
                            color: Colors.black,
                            child: Icon(Icons.add,color: Colors.white,),
                          ),
                          Text("add more"),
                        ],
                      ),
                    ),
                  ),)
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class ItemButton extends StatefulWidget {
  final ItemCallback onCrossSelect;
  final UniqueKey id;
  final int? initialItem;
  const ItemButton({Key? key, required this.onCrossSelect, required this.id, this.initialItem}) : super(key: key);

  @override
  _ItemButtonState createState() => _ItemButtonState();
}

typedef ItemCallback = void Function(UniqueKey count);

class _ItemButtonState extends State<ItemButton> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(8),
      child: Stack(
        children: [
          GestureDetector(
            onTap: () async {

            },
            child: Container(
              height: 90,
              width: 110,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15),
                color: Colors.grey,
              ),
              child: Center(child: Text("${widget.id}",style: TextStyle(
                color: Colors.black,
                fontSize: 20
              ),)),
            ),
          ),
          widget.initialItem == 0
              ? Container()
              : Positioned(
            top: 0,
              left: 0,
              child: GestureDetector(
            onTap: () {
              widget.onCrossSelect(widget.id);
              print("${widget.id}");
            },
                child: Icon(Icons.close,
                color: Colors.black,
                size: 30,),

          ))
        ],
      ),
    );
  }
}

The problem is here where you define an empty container:

widget.initialItem == 0
              ? Container()
              : Positioned(

If you remove this and keep everything as expected you dont have the space. Since you are using Wrap Widget the empty container also acts as child adjacent to the previous child in the main axis, given by direction, leaving spacing space in between.

在此处输入图像描述 From the documentation:

If there is not enough space to fit the child, Wrap creates a new run adjacent to the existing children in the cross axis.

removing this line in your code you don't have any empty space as behavior in your UI. Read more here

So after all using flutter tools, I found the issue is with an empty container

widget.initialItem == 0
              ? Container()
              : Positioned()

so this container takes the entire width so i just add height = 0, width = 0, now its fine its working upto my expectations

widget.initialItem == 0
                  ? Container(height = 0, width = 0)
                  : Positioned()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM