如何在Flutter的轮播组件中增加图片的宽度和高度,而不给轮播组件指定高度?

3
我需要构建一个走马灯滑块,其中包含图像和图像下方的文本,并且图像的约束需要为250 x 250。我已经将图像和文本放在列中,但是它们被切掉了,显示底部发生了溢出。如果给CarouselSlider小部件设置高度,它就可以工作,但是我不应该这样做,因为文本会有所变化,给定高度不会保持一致。尝试了其他几种方法,如Wrap、Expanded等,但都无法解决问题。
这是我的实现方式:
final List<String> imgList = [
  'https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80',
  'https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80',

];

  Widget build(BuildContext context) {
    return Container(
       child: CarouselSlider(
          //height: 350,   //giving this a height fixes it but I shouldn't be doing it
          items: imgList.map((i) {
           return 
                Column(
                  children: [
                    Container(
                     margin: EdgeInsets.symmetric(horizontal: 5.0),
                      child: ClipRRect(
                         borderRadius: BorderRadius.circular(16.0),
                         child: Image.network(i,  height: 250, width: 250)),
                    ),
                    Text(i)
                  ],
                );

          }).toList(),
          viewportFraction: 1.0,
      )

2个回答

5

使用 FittedBox 包装容器和使用 Flexible 包装容器有不同的效果
你可以查看演示图片并在自己的案例中使用

Column(
                  children: <Widget>[
                    FittedBox(
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        margin: EdgeInsets.symmetric(horizontal: 10.0),
                        decoration: BoxDecoration(
                          color: Colors.green,
                        ),
                        child: Image.network(
                          imageUrl.sponsorlogo,
                          height: 250,
                          width: 250,
                          //fit: BoxFit.fill,
                        ),
                      ),
                    ),
                    Text(imageUrl.toString()),
                  ],
                );

这里输入图片描述

使用 Flexible 包装

return Column(
                  children: <Widget>[
                    Flexible(
                      child: Container(
                        width: MediaQuery.of(context).size.width,
                        margin: EdgeInsets.symmetric(horizontal: 10.0),
                        decoration: BoxDecoration(
                          color: Colors.green,
                        ),
                        child: Image.network(
                          imageUrl.sponsorlogo,
                          height: 250,
                          width: 250,
                          //fit: BoxFit.fill,
                        ),
                      ),
                    ),
                    Text(imageUrl.toString()),
                  ],
                );

输入图像描述

完整测试代码

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:http/http.dart' as http;
//
//     final payload = payloadFromJson(jsonString);

import 'dart:convert';

List<Payload> payloadFromJson(String str) =>
    List<Payload>.from(json.decode(str).map((x) => Payload.fromJson(x)));

String payloadToJson(List<Payload> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Payload {
  String sponsorlogo;

  Payload({
    this.sponsorlogo,
  });

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        sponsorlogo: json["sponsorlogo"] == null ? null : json["sponsorlogo"],
      );

  Map<String, dynamic> toJson() => {
        "sponsorlogo": sponsorlogo == null ? null : sponsorlogo,
      };
}

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: SponsorSlider(),
    );
  }
}

class SponsorSlider extends StatefulWidget {
  @override
  _SponsorSliderState createState() => _SponsorSliderState();
}

class _SponsorSliderState extends State<SponsorSlider> {
  Future<List<Payload>> getSponsorSlide() async {
    //final response = await http.get("getdata.php");
    //return json.decode(response.body);
    String response =
        '[{"sponsorlogo":"https://images.unsplash.com/photo-1520342868574-5fa3804e551c?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=6ff92caffcdd63681a35134a6770ed3b&auto=format&fit=crop&w=1951&q=80"},{"sponsorlogo":"https://images.unsplash.com/photo-1522205408450-add114ad53fe?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=368f45b0888aeb0b7b08e3a1084d3ede&auto=format&fit=crop&w=1950&q=80"},{"sponsorlogo":"https://images.unsplash.com/photo-1519125323398-675f0ddb6308?ixlib=rb-0.3.5&ixid=eyJhcHBfaWQiOjEyMDd9&s=94a1e718d89ca60a6337a6008341ca50&auto=format&fit=crop&w=1950&q=80"}]';
    var payloadList = payloadFromJson(response);
    return payloadList;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Card(
          child: new FutureBuilder<List<Payload>>(
            future: getSponsorSlide(),
            builder: (context, snapshot) {
              if (snapshot.hasError) print(snapshot.error);
              return snapshot.hasData
                  ? new SponsorList(
                      list: snapshot.data,
                    )
                  : new Center(child: new CircularProgressIndicator());
            },
          ),
        ),
      ),
    );
  }
}

class SponsorList extends StatefulWidget {
  final List<Payload> list;
  SponsorList({this.list});

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

class _SponsorListState extends State<SponsorList> {
  int _current = 0;

  int index = 1;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          CarouselSlider(
            //height: 200.0,
            initialPage: 0,
            onPageChanged: (index) {
              setState(() {
                _current = index;
              });
            },
            autoPlay: true,
            autoPlayInterval: Duration(seconds: 2),
            reverse: false,
            items: widget.list.map((imageUrl) {
              return Builder(builder: (BuildContext context) {
                return Column(
                  children: <Widget>[
                      Flexible(
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          margin: EdgeInsets.symmetric(horizontal: 10.0),
                          decoration: BoxDecoration(
                            color: Colors.green,
                          ),
                          child: Image.network(
                            imageUrl.sponsorlogo,
                            height: 250,
                            width: 250,
                            //fit: BoxFit.fill,
                          ),

                    ),
                      ),
                    Text(imageUrl.toString()),
                  ],
                );
              });
            }).toList(),
          )
        ],
      ),
    );
  }
}

0

尝试使用这个包来实现更好的效果:https://pub.dev/packages/shimmer

CarouselSlider(
                        options: CarouselOptions(
                          enlargeCenterPage: true,
                          height: MediaQuery.of(context).size.height / 3.5,
                        ),
                        items: _imgList
                            .map(
                              (item) => Container(
                                margin: EdgeInsets.all(4),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(10),
                                  child: CachedNetworkImage(
                                    filterQuality: FilterQuality.low,
                                    fit: BoxFit.cover,
                                    imageUrl: item,
                                    placeholder: (context, url) =>
                                        Shimmer.fromColors(
                                      baseColor: Colors.grey[300],
                                      highlightColor: Colors.white,
                                      child: Container(
                                        color: Colors.white,
                                      ),
                                    ),
                                    errorWidget: (context, url, error) =>
                                        Text('Unknown image type !'),
                                  ),
                                ),
                              ),
                            )
                            .toList(),
                      ),

虽然这段代码片段可能是解决方案,但包括详细的解释真的有助于提高您的帖子质量。请记住,您正在回答未来读者的问题,而这些人可能不知道您提出代码建议的原因。 - Shawn Hemelstrand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接