Home > Blockchain >  setState() called in constructor:
setState() called in constructor:

Time:11-29

I try to change text with a listTile in another class but i receive the error

═══════ Exception caught by gesture ═══════════════════════════════════════════
setState() called in constructor: RightSideState#46ecc(lifecycle state: created, no widget, not mounted)
════════════════════════════════════════════════════════════════════════════════

I have 2 class RightSide and LeftSide, the ListTile is in a LeftSide and the text to change is in a Right Side

LeftSide:

class LeftSide extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => LeftSideState();
}

class LeftSideState extends State<LeftSide> {
  RightSideState r = new RightSideState();
  @override
  Widget build(BuildContext context) {
    return SizedBox(
        width: 350,
        child: Container(
          color: Color.fromARGB(255, 241, 160, 29),
          padding: EdgeInsets.all(30),
          child: ListView(
            scrollDirection: Axis.vertical,
            children: <Widget>[
              for (int i = 0; i < 15; i  )
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                  child: Container(
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(12),
                          color: Colors.indigo),
                      child: ListTile(
                        title: Center(
                            child: Text('asdfadfadx',
                                style: TextStyle(fontSize: 16.0))),
                        leading: Icon(
                          Icons.account_circle_rounded,
                          size: 30,
                        ),
                        trailing: Icon(Icons.arrow_forward_ios),
                        textColor: Colors.white,
                        iconColor: Colors.white,
                        onTap: r.showText,
                      )),
                )
            ],
          ),
        ));
  }
}

RightSide:

class RightSide extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => RightSideState();
}

class RightSideState extends State<RightSide> {
  String nome = 'mkh';
  void showText() {
    print('start');
    setState(() {
      nome = 'sdasdfad';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: Container(
      color: Color.fromARGB(255, 241, 170, 29),
      child: Padding(
        padding: EdgeInsets.only(top: 80, left: 30),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Text(
            nome,
            style: TextStyle(fontSize: 40, color: Colors.indigo),
          ),
          Text(''   ''   ''   '',
              style: TextStyle(fontSize: 24, color: Colors.indigo)),
          Text(''   '',
              style: TextStyle(fontSize: 24, color: Colors.indigo)),
          Text(
              ''  
                  ''  
                  ''  
                  ''  
                  ''  
                  '',
              style: TextStyle(fontSize: 24, color: Colors.indigo)),
          Text(''   '',
              style: TextStyle(fontSize: 24, color: Colors.indigo)),
          Text(''   '',
              style: TextStyle(fontSize: 24, color: Colors.indigo)),
        ]),
      ),
    ));
  }
}

I try to create the class extends StatefulWidget and the class RightSideState and LeftSideState

CodePudding user response:

So your main problem is that you want to call a method in RightSide's state from LeftSide's state. To do this you can make use of a GlobalKey. You create a key for the RightSide and you give that same key as an extra variable to the other side. With that key you can access the state of it. LeftSide and RightSide must have some common parent somewhere in the widget tree. There is where you will need to create the key and pass them. Here is a minimum full working example of how to do it. I'm not using the same LeftSide and RightSide as you but simplified them, but I hope you'll get the point and can apply similar logic in your code:

import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: MyApp()));

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  GlobalKey<RightSideState> key = GlobalKey<RightSideState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Column(
            children: [
              LeftSide(rightSideKey: key),
              RightSide(key: key)
            ]));
  }
}

class LeftSide extends StatefulWidget {
  final GlobalKey<RightSideState> rightSideKey;

  const LeftSide({Key? key, required this.rightSideKey}) : super(key: key);

  @override
  State<LeftSide> createState() => LeftSideState();
}

class LeftSideState extends State<LeftSide> {
  @override
  Widget build(BuildContext context) {
    return TextButton(
        onPressed: () => widget.rightSideKey.currentState?.showText(),
        child: const Text("click"));
  }
}

class RightSide extends StatefulWidget {
  const RightSide({Key? key}) : super(key: key);

  @override
  State<RightSide> createState() => RightSideState();
}

class RightSideState extends State<RightSide> {
  String nome = 'mkh';

  void showText() {
    print('start');
    setState(() {
      nome = 'sdasdfad';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(nome);
  }
}
  • Related