swamper
swamper

Reputation: 117

How to position text widget in stack for different screen sizes in flutter?

I'm trying to place some text over the image and due to variable screen size the text widget balance for one screen sizes not balacing in someother screen sizes.

The output I need is like the image

enter image description here

I'm using name in place of "Some text here". So, I tried balance the text widget with my code and now I tested on another device with different screen size and the "Some text here" came to the inner red border bottom.

How to solve this thing? I've tried some code and let me place it for you.

Widget imageStack() {
    print("Width: " + (MediaQuery.of(context).size.width).toString());
    return
        // Padding(
        //   padding: EdgeInsets.only(top: MediaQuery.of(context).size.height / 4),
        //   child:
        AspectRatio(
      aspectRatio: 1,
      child: SizedBox(
        // height: 700,
        width: 170,
        child: Stack(
          // fit: StackFit.loose,
          alignment: Alignment.center,
          children: [
            Positioned(
              top: 120,
              left: MediaQuery.of(context).size.width / 4 + 20,
              child: Align(
                  alignment: Alignment.center,
                  child: Image(
                    width: 150,
                    height: 200,
                    fit: BoxFit.cover,
                    image: NetworkImage(data['image']),
                  )),
            ),
            const Positioned.fill(
                child: Align(
                    alignment: Alignment.centerRight,
                    child: Image(
                        image: AssetImage('assets/images/fomat.png')))),
            Positioned(
              // top: MediaQuery.of(context).size.height / 2.68,
              top: MediaQuery.of(context).size.width <= 395
                  ? 295
                  : 295 + MediaQuery.of(context).size.height / 48,
              child: Align(
                alignment: Alignment.center,
                child: Text(data['name'],
                    style: GoogleFonts.poppins(
                      fontSize: 20,
                      // fontSize: 24,
                      fontWeight: FontWeight.w600,
                    )),
              ),
            ),
            Positioned(
              top: 25,
              right: 25,
              child: Align(
                // alignment: Alignment.topRight,
                child: Text(
                  dob.toString(),
                  style: GoogleFonts.lato(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
      // ),
    );
  }

  dynamic directory;
  imageShareReady() async {
    directory = await getApplicationDocumentsDirectory();
  }

  final screenshotController = ScreenshotController();
  late Uint8List _imageFile;

  _saveImage(Uint8List bytes) async {
    final result = await ImageGallerySaver.saveImage(_imageFile);
    print("Result: " + result.toString());
    ScaffoldMessenger.of(context)
        .showSnackBar(SharedManager().showSnackBar("Image Saved to gallery!"));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Column(
        // mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            height: MediaQuery.of(context).size.height / 4,
          ),
          Screenshot(controller: screenshotController, child: imageStack()),
        ],
      ),
      floatingActionButton: SpeedDial(
        backgroundColor: ColorsManager.appColor,
        animatedIcon: AnimatedIcons.menu_close,
        children: [
          SpeedDialChild(
            onTap: () {
              // Navigator.of(context).pop();
              // screenshotController
              //     .captureFromWidget(imageStack())
              //     .then((image) {
              //   setState(() {
              //     _imageFile = image;
              //     _saveImage(_imageFile);
              //   });
              // });
              screenshotController.capture().then((image) {
                setState(() {
                  _imageFile = image!;
                  _saveImage(_imageFile);
                });
              }).catchError((onError) {
                print("Error: " + onError.toString());
              });
            },
            child: const Icon(
              Icons.save,
              color: Colors.white,
            ),
            backgroundColor: ColorsManager.appColor,
          ),
          SpeedDialChild(
            onTap: () async {
              // screenshotController
              //     .captureFromWidget(imageStack())
              //     .then((image) {
              //   setState(() {
              //     final imageFileSave = File(
              //         '${directory.path}/${DateTime.now().millisecondsSinceEpoch}.png');
              //     imageFileSave.writeAsBytesSync(image);
              //     Share.shareFiles([imageFileSave.path]);
              //   });
              // });
              screenshotController.capture().then((image) {
                setState(() {
                  final imageFileSave = File(
                      '${directory.path}/${DateTime.now().millisecondsSinceEpoch}.png');
                  imageFileSave.writeAsBytesSync(image!);
                  Share.shareFiles([imageFileSave.path]);
                });
              });
            },
            child: const Icon(
              Icons.share,
              color: Colors.white,
            ),
            backgroundColor: ColorsManager.appColor,
          ),
        ],
      ),
      // ),
    );
  }

Upvotes: 0

Views: 1006

Answers (1)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63809

I am using LayoutBuilder to get the size. I will encourage you to check Align widget.

 
class ImageStack extends StatelessWidget {
  const ImageStack({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return Stack(
          children: [
            ///Background image
            Container(
              decoration: BoxDecoration(
                  border: Border.all(width: 12, color: Colors.red)),
            ),
            Align(
              /// positioded the column
              alignment: Alignment(0, .1),

              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  /// inner container
                  Container(
                    height: constraints.maxHeight / 3,
                    width: constraints.maxWidth / 3,
                    decoration: BoxDecoration(
                        border: Border.all(width: 12, color: Colors.red)),
                  ),
                  Text(
                    "Some Text here",
                    style: TextStyle(
                      fontSize:
                          constraints.maxHeight * .1, // change the font size
                      fontWeight: FontWeight.bold,
                    ),
                  ),

                  Divider(
                    color: Colors.black,
                    indent: constraints.maxWidth * .1,
                    endIndent: constraints.maxWidth * .1,
                  ),
                ],
              ),
            )
          ],
        );
      },
    );
  }
}

And you

  SizedBox(
            width: 400,
            height: 400,
            child: ImageStack(),
          ),

enter image description here

If you want more control, you can use also use FittedBox, auto_text_size or

  SizedBox(
                    width: constraints.maxWidth * .8,
                    child: Text(
                      "Some Text here",
                      style: TextStyle(
                        fontSize: constraints.maxHeight * .05 +
                            constraints.maxWidth * .05, // change the font size
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),

Upvotes: 1

Related Questions