简体   繁体   中英

onChanged doesn't work while assigning a value to a variable flutter

I have to use call back to raise the variable value, but while I am trying to test that if my variable gets initialized of not using a print statement, it returns null which means the variable is not initialized. //Here is my code: note that I have a variable in the body of my context which is:

String? newTaskTitle;

TextField(
          cursorColor: Colors.white38,
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.white38),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.white38),
            ),
          ),
          textAlign: TextAlign.center,
          autofocus: true,
          onChanged: (newText) {
            newTaskTitle = newText;
          },
        ),
        FlatButton(
          color: Colors.white,
            onPressed: () {
            print(newTaskTitle);
            },
            child: const Text('Add',
              style: TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
        ),

when you define newTaskTitle inside body, every time keyboard open and close, your widget rebuild and newTaskTitle define again. You should define newTaskTitle outside build method like this:

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

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  String newTaskTitle = '';//<---- define here
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        TextField(
          cursorColor: Colors.white38,
          decoration: const InputDecoration(
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.white38),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: BorderSide(color: Colors.white38),
            ),
          ),
          textAlign: TextAlign.center,
          autofocus: true,
          onChanged: (newText) {
            newTaskTitle = newText;
          },
        ),
        FlatButton(
          color: Colors.white,
          onPressed: () {
            print(newTaskTitle);
          },
          child: const Text(
            'Add',
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
        ),
      ]),
    );
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM