Home > Software design >  Fix width in Stack to width of first child
Fix width in Stack to width of first child

Time:04-27

I got a Stack-Widget with two childs. The first one is an image, the second one is text. I want to place the text on top of the image, hence the Stack. But when the text is quite long, the text overflows on the left and right. I want it to stay on the image. How can I limit the stacks width to the width of the image?

My Code:

Stack(
  alignment: Alignment.bottomCenter,
  children: [
    ExtendedImage.network(
      UserSession().currentImgURL!,
      fit: BoxFit.fitWidth,
      cache: true,
      cacheWidth: 1000,
      enableMemoryCache: false,
      enableLoadState: true,
    ),
    OutlinedText(
      text: Text(title, style: TextStyle(fontSize: kIsWeb ? 5.sp : 18.sp, height: 1.1)),
      strokes: [
        OutlinedTextStroke(color: Colors.black, width: 5),
      ],
    )
  ],
)

enter image description here

CodePudding user response:

Use Positioned

Example

import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  static MyAppState? of(BuildContext context) =>
      context.findAncestorStateOfType<MyAppState>();

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

class MyAppState extends State<MyApp> {
  final controller = TextEditingController(text: 'ABC');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Center(
          child: Stack(
//           fit: StackFit.expand,
            children: [
              Image.network(
                'https://i0.wp.com/static1.srcdn.com/wordpress/wp-content/uploads/2021/03/Among-Us-Random-Name-Generator.jpg?w=750&ssl=1',
                fit: BoxFit.cover,
              ),
              Positioned(
                left: 0,
                right: 0,
                bottom: 0,
                child: Text(
                  'bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla',
                  style: TextStyle(color: Colors.white, fontSize: 30),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

enter image description here

  • Related