Skip to main content

Flutter Fix Incorrect use of ParentDataWidget Expanded Error

Hello friends, Today when I was creating a flutter tutorial with Expanded widget then by mistake I defined Expanded directly inside Body section of app. Then I have defined a Container widget as child of Expanded. My goal is to achieve 50% of device height and width using Flex. But I encountered a error and my app crashed. The error is "Another exception was thrown: Incorrect use of ParentDataWidget".
Screenshot of Error in app:
Flutter Fix Incorrect use of ParentDataWidget Expanded Error
Screenshot of Error in Terminal:

Flutter Fix Incorrect use of ParentDataWidget Expanded Error

1. To Fix this error we have to wrap Expanded widget inside Column or Row widget.
Column(children: [
      Expanded(
          flex: 1,
          child: Container(
            width: double.infinity,
            color: Colors.green,
            alignment: AlignmentDirectional.center,
            child: Text('hello'),
          )),
      Expanded(
          flex: 1,
          child: Container(
            width: double.infinity,
            color: Colors.red,
            alignment: AlignmentDirectional.center,
            child: Text('hello'),
          ))
    ])
Source code for main.dart file:
import 'package:flutter/material.dart';

void main() => runApp(const App());

class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            body: Center(
                child: Column(children: [
      Expanded(
          flex: 1,
          child: Container(
            width: double.infinity,
            color: Colors.green,
            alignment: AlignmentDirectional.center,
            child: Text('hello'),
          )),
      Expanded(
          flex: 1,
          child: Container(
            width: double.infinity,
            color: Colors.red,
            alignment: AlignmentDirectional.center,
            child: Text('hello'),
          ))
    ]))));
  }
}

Comments