TextField в StatelessWidget возвращает значение null при печати - PullRequest
0 голосов
/ 01 августа 2020

Я пытаюсь напечатать newTaskTitle , то есть текст, полученный из текстового поля. Это виджет без сохранения состояния. Но когда срабатывает нажатие кнопки, печатается null . Также печать значение правильно печатает набранный текст.


class AddTaskScreen extends StatelessWidget {
  String newTaskTitle; 
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Color(0xFF757575),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20.0),
            topRight: Radius.circular(20.0),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Text(
              'Add Task',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.lightBlueAccent,
                fontSize: 30.0,
              ),
            ),
            TextField(
              textAlign: TextAlign.center,
              onChanged: (value) {
                newTaskTitle = value;
              },
            ),
            SizedBox(
              height: 10.0,
            ),
            FlatButton(
              child: Text(
                'Add',
                style: TextStyle(color: Colors.white),
              ),
              color: Colors.lightBlueAccent,
              onPressed: () {
                print(newTaskTitle); //This printing null...
              },
            )
          ],
        ),
      ),
    );
  }
}

Это результат Android Studio

W/IInputConnectionWrapper(11205): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(11205): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper(11205): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(11205): endBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(11205): beginBatchEdit on inactive InputConnection
W/IInputConnectionWrapper(11205): getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper(11205): getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper(11205): getSelectedText on inactive InputConnection
W/IInputConnectionWrapper(11205): endBatchEdit on inactive InputConnection
I/flutter (11205): null```

Ответы [ 2 ]

0 голосов
/ 01 августа 2020
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello You',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new HelloYou(),
    );
  }
}

class HelloYou extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HelloYouState();
}

class _HelloYouState extends State<HelloYou> {

  String newTaskTitle = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("HelloYou App !"),
        backgroundColor: Colors.green,
      ),
      body: Container(
          padding: EdgeInsets.all(15.0),
          child: Column(
            children: <Widget>[
              TextField(
                onChanged: (str) {
                  setState(() {
                    newTaskTitle = str;
                  });
                },
              ),
              FlatButton(
              child: Text(
                'Add',
                style: TextStyle(color: Colors.white),
              ),
              color: Colors.lightBlueAccent,
              onPressed: () {
                print(newTaskTitle);
              },
            )

            ],
          )),
    );
  }
}

Пожалуйста, проверьте мой код. Вы можете использовать StatefulWidget

0 голосов
/ 01 августа 2020

Используйте TextEditingController:

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

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

class _MyWidgetState extends State<MyWidget> {
  final _textEditingController = TextEditingController();
  
  @override
  void dispose() {
    _textEditingController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextField(
          controller: _textEditingController,
          textAlign: TextAlign.center,
        ),
        FlatButton(
          onPressed: () => print(_textEditingController.text),
          child: Text("Press Me"),
        ),
      ],
    );
  }
}
...