首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在不给carouselSlider设置高度的情况下在Flutter的旋转木马滑块中增加图像的宽度和高度

如何在不给carouselSlider设置高度的情况下在Flutter的旋转木马滑块中增加图像的宽度和高度
EN

Stack Overflow用户
提问于 2019-10-25 07:14:05
回答 2查看 10.3K关注 0票数 1

我需要建立一个旋转木马滑块下的图像和文本的图像和图像约束需要是250 x 250。我有一个列中的图像和文本,但它们被切断了,说底部有一个溢出。如果我给CarouselSlider小部件一个高度,它是有效的,但是我不应该这样做,因为文本不同,并且给出一个高度不会是consistent.Tried几种其他方法,如换行,展开,但似乎都不起作用

我是这样做的::

代码语言:javascript
运行
复制
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,
      )
EN

回答 2

Stack Overflow用户

发布于 2019-10-25 09:42:56

用FittedBox包装容器和用柔性包装效果不同

您可以查看演示图片并在您的案例中使用

代码语言:javascript
运行
复制
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()),
                  ],
                );

使用灵活的包装

代码语言:javascript
运行
复制
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()),
                  ],
                );

完整的测试代码

代码语言:javascript
运行
复制
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(),
          )
        ],
      ),
    );
  }
}
票数 4
EN

Stack Overflow用户

发布于 2021-05-04 19:40:24

尝试这样做,并将此包与其一起使用,以获得更好的效果:https://pub.dev/packages/shimmer

代码语言:javascript
运行
复制
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(),
                      ),
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58550283

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档