Tired of UI elements being overwritten in your Flutter app when using Stack? Learn how to prevent children from overlapping each other with this simple solution. Click to find out more.
Steps to Prevent Stack Children in Flutter
If you facing the problem by using stack , means you need to follow proper guide of the stack. Means if you passing children insiding stack you have to wrap child with positioned widgets.
Issue on code by using stack
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(
children:const [
Text(
'Hello world !',
),
Text(
'How are you ? ',
),
]
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
Check Out: [Solved] RenderBox was not laid out in Flutter
Solution
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(
children: const [
Positioned(
left: 10,
top: 10,
child: Text(
'Hello world !',
),
),
Positioned(
left: 10,
top: 40,
child: Text(
'How are you ? ',
),
),
],
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}