Home > Enterprise >  Flutter RenderFlex and setState issue while doing buttons and callbacks
Flutter RenderFlex and setState issue while doing buttons and callbacks

Time:12-25

Hello I am getting two errors on my code, this code should produce a input box where when the information is submitted via a button it pushes that to the body of the page.

The issues are:

The following assertion was thrown during layout: A RenderFlex overflowed by 99359 pixels on the bottom. The following assertion was thrown building TextInputWidget(dirty, state: _TextInputWidgetState#e5726): setState() or markNeedsBuild() called during build.

main.dart:


void main() {
  runApp(const MyApp());
}

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.orange,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String text = "";

  void changeText(String text) {
    this.setState(() {
      this.text = text;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Hello World!'),
      ),
      body: Column(
        children: <Widget>[
          TextInputWidget(this.changeText),
          Text(this.text),
        ],
      ),
    );
  }
}

class TextInputWidget extends StatefulWidget {
  final Function(String) callback;

  TextInputWidget(this.callback);

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

class _TextInputWidgetState extends State<TextInputWidget> {
  final controller = TextEditingController();

  @override
  void dispose() {
    super.dispose();
    controller.dispose();
  }

  click() {
    widget.callback(controller.text);
    controller.clear();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
        controller: this.controller,
        decoration: InputDecoration(
            prefixIcon: Icon(Icons.message),
            labelText: "Type a message.",
            suffixIcon: IconButton(
              icon: Icon(Icons.send),
              splashColor: Colors.orange,
              tooltip: "Post message",
              onPressed: this.click(),
            )));
  }
}

CodePudding user response:

The issue is coming from onPressed: this.click(),. It is calling/running the method while first build, but you wish to call it when button is pressed, in this case do it like.

onPressed: click,

If you like to have move things inside onPressed do it like

onPressed: () {
  click();
},
  • Related