Flutter Card内容在水平列表视图中未居中

qmelpv7a  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(187)

我的Flutter应用程序有一个布局问题。我创建了一个MyCardWidget,其中包含一个Card小部件。在卡片内部,我尝试使用列和mainAxisAlignment将其内容居中:MainAxisAlignment.center和crossAxisAlignment:CrossAxisAlignment.center.但是,当我将多个MyCardWidget示例放在一个水平ListView中时,卡片的位置并没有像预期的那样居中。

builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(child: CircularProgressIndicator());
        } else if (snapshot.hasError) {
          return Center(child: Text('Hata: ${snapshot.error.toString()}'));
        } else {
          return Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('lib/assets/images/home.jpg'),
                  fit: BoxFit.cover,
                ),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text("Istanbul 20"),
                  SizedBox(
                    width: MediaQuery.of(context).size.width,
                    height: 150,
                    child:   Obx(() => ListView(
                      scrollDirection: Axis.horizontal,
                      children: cards
                          .map((card) => card)
                          .toList(),
                    )),
                  )

这是卡Widget

class _MyCardWidgetState extends State<MyCardWidget> {
  @override
  Widget build(BuildContext context) {
    return Card(

      color: Colors.transparent,
      elevation: 2,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,  // <-- Bu satırı ekledik
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Image.network(
              "https://openweathermap.org/img/wn/${widget.icon}@2x.png"),
          Text(widget.temp.value),
          // Diğer String verilerini kullanabilirsiniz
        ],
      ),
    );
  }
wxclj1h5

wxclj1h51#

使用Center小部件 Package ListView,并在ListView上添加shrinkWrap: true

child: Center(
  child: ListView(
    scrollDirection: Axis.horizontal,
    shrinkWrap: true, //not so optimal but work out
    children: [

相关问题