0

in my flutter code below i'm suffering from height and width problem which appears different on each device, for ex in my below code i set a background image and it appears on half screen if i didn't set a height, and ofc this height appears different on each device. also in child: Image.asset( object["placeImage"], fit: BoxFit.cover,width: 280,height: 180,) i wanted the image to appear one size on all devices without setting a specific height and width.. is there a way to do this in flutter?

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,
          )),
    );
  }
}
Mustafa
  • 41
  • 5

1 Answers1

2

if you want you image to same size in every device wrap it with a container and give static height and width use the fit property according to your needs but if you want the size of the image should change according to device height and width you can use media query for that ....for eg

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

put your image in child parameter ...... let me know if this help

Vishal_VE
  • 1,852
  • 1
  • 6
  • 9