【问题标题】:Flutter: responsive height and widthFlutter:响应式高度和宽度
【发布时间】:2022-01-16 20:41:27
【问题描述】:

在我下面的颤动代码中,我遇到了高度和宽度问题,这在每个设备上看起来都不同,例如,在下面的代码中,我设置了一个背景图像,如果我没有设置高度,它会出现在半屏上,并且这个高度在每个设备上看起来都不同。 同样在child: Image.asset( object["placeImage"], fit: BoxFit.cover,width: 280,height: 180,) 中,我希望图像在所有设备上都显示为一种尺寸,而无需设置特定的高度和宽度。有没有办法在颤动中做到这一点?

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:localize_and_translate/localize_and_translate.dart';
import 'package:menu_app/About.dart';
import 'package:menu_app/Drinks.dart';
import 'package:flutter/gestures.dart';

class FoodDetailsPage extends StatefulWidget {
  final String pageId;
  //The string of each meal will be passed when calling this page.
  FoodDetailsPage({required this.pageId});

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

class _FoodDetailsPageState extends State<FoodDetailsPage> {
  late Future<List<Widget>> myCreateList;
  @override
  void initState() {
    super.initState();
    myCreateList = createList();
    //THIS IS NECESSARY TO AVOID THE FUTUREBUILDER FROM FIRING EVERYTIME THE PAGE REBUILDS.
    // You can check more at
    // https://stackoverflow.com/questions/57793479/flutter-futurebuilder-gets-constantly-called
  }

  Future<List<Widget>> createList() async {
    List<Widget> items = <Widget>[];
    String dataString = await rootBundle.loadString(translator.translate(
        "assets/${widget.pageId}.json")); //view JSON file depending on pageId
    List<dynamic> dataJSON = jsonDecode(dataString);

    dataJSON.forEach((object) {
      String finalString = "";
      List<dynamic> dataList = object["placeItems"];
      dataList.forEach((item) {
        finalString = finalString + item + " | ";
      });

      items.add(Padding(
        padding: EdgeInsets.all(2.0),
        child: Container(
          decoration: BoxDecoration(
              color: Color.fromRGBO(255, 255, 255, 0.7),
              borderRadius: BorderRadius.all(Radius.circular(10.0)),
              boxShadow: [
                BoxShadow(
                    color: Colors.black12, spreadRadius: 2.0, blurRadius: 5.0),
              ]),
          margin: EdgeInsets.all(5.0),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
           
                child: Image.asset(
                  object["placeImage"], // also here i need to set a astatic height and width on each device
                  fit: BoxFit.cover,
                  width: 280,
                  height: 180,
                ),
              ),
              SizedBox(
                width: 250,
                child: Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        translator.translate(object["placeName"]),
                        style: GoogleFonts.elMessiri(
                            textStyle: TextStyle(
                                fontSize: 15.0, color: Colors.black54)),
                      ),
                      // Padding(
                      //   padding: const EdgeInsets.only(top: 2.0, bottom: 2.0),
                      //   child: Text(
                      //     finalString,
                      //     overflow: TextOverflow.ellipsis,
                      //     style: TextStyle(
                      //       fontSize: 12.0,
                      //       color: Colors.black54,
                      //     ),
                      //     maxLines: 1,
                      //   ),
                      // ),
                      Text(
                        translator.translate(" ${object["minOrder"]} IQD"),
                        style: TextStyle(fontSize: 12.0, color: Colors.black54),
                      )
                    ],
                  ),
                ),
              )
            ],
          ),
        ),
      ));
    });

    return items;
  }

  Widget build(BuildContext context) {
    // ignore: unused_local_variable

    var size = MediaQuery.of(context).size;
    var screenHeight = MediaQuery.of(context).size.height;

    var screenWidth = MediaQuery.of(context).size.width;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: HexColor("#242424"),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          iconSize: 20.0,
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              "assets/images/logo.png",
              fit: BoxFit.contain,
              height: 40,
            ),
          ],
        ),
      ),
      body: SafeArea(
          child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min, // set min
          children: <Widget>[
            Container(
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: AssetImage(
                        "assets/images/backg.png", // i have to set a static height for each device to get the full backfround 
                      ),
                      fit: BoxFit.fill)),
              height: 3000, 
              width: screenWidth,
              child: FutureBuilder<List<Widget>>(
                  initialData: [Text("")],
                  future: myCreateList,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting)
                      return Text(translator.translate("Loading"));

                    if (snapshot.hasError) {
                      return Text("Error ${snapshot.error}");
                    }
                    if (snapshot.hasData) {
                      return Padding(
                          padding: EdgeInsets.all(8.0),
                          child: GridView.count(
                            childAspectRatio: 1, // items' width/height
                            crossAxisCount: 2,
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            children: [
                              // ignore: sdk_version_ui_as_code
                              ...?snapshot.data,
                            ],
                          ));
                    } else {
                      return CircularProgressIndicator();
                    }
                  }),
            )
          ],
        ),
      )),
      floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => About()),
            );
          },
          backgroundColor: Colors.black,
          child: Icon(
            MdiIcons.information,
            color: Colors.white,
          )),
    );
  }
}

【问题讨论】:

  • 试试这个包,sizer:^2.0.15

标签: flutter dart


【解决方案1】:

如果您希望每个设备中的图像尺寸相同,请使用容器将其包装并提供静态高度和宽度,根据您的需要使用 fit 属性,但如果您希望图像的大小应根据设备的高度和宽度而变化您可以为此使用媒体查询....例如

Container(
        color: Colors.yellow,
        height: MediaQuery.of(context).size.height * 0.65,
        width: MediaQuery.of(context).size.width,
      )

将您的图像放入子参数中...... 让我知道这是否有帮助

【讨论】:

  • 高度在设备上仍然显示不同:\
猜你喜欢
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2016-08-30
  • 2015-03-01
  • 1970-01-01
  • 2016-03-09
  • 1970-01-01
相关资源
最近更新 更多