不可为 null 的局部变量 'title' 必须先赋值,然后才能使用。颤动错误

The non-nullable local variable 'title' must be assigned before it can be used. Flutter error

我想从 textfield widget 获取用户输入并在 title 变量中赋值,如此代码

import 'package:flutter/material.dart';

class AddTaskScreen extends StatelessWidget {
  final Function callBack; // function

  AddTaskScreen({required this.callBack});

  @override
  Widget build(BuildContext context) {
    String title; // declaring the variable
    return Container(
      height: 350,
      color: Color(0xff757575),
      child: Container(
        padding: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(20),
            topLeft: Radius.circular(20),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              'Add Task',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.lightBlueAccent,
                fontSize: 24,
              ),
            ),
            SizedBox(
              height: 20,
            ),
            TextField(
              textAlign: TextAlign.center,
              autofocus: false,
              style: TextStyle(
                color: Colors.black,
                fontSize: 15,
              ),
              onChanged: (value) {
                title = value; // taking the user input
              },
              decoration: InputDecoration(
                focusColor: Colors.lightBlueAccent,
                hintText: 'Type a Task',
                hintStyle: TextStyle(
                  color: Colors.grey,
                  fontSize: 12,
                ),
              ),
            ),
            SizedBox(
              height: 20,
            ),
            TextButton(
              onPressed: () {
                callBack(title); // error
              },
              style: TextButton.styleFrom(
                backgroundColor: Colors.lightBlueAccent,
              ),
              child: Text(
                'Add',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

如您所见,有一个函数 callBack 变量。当我在此函数中传递 title 时,它具有 String 参数,它会给我一个警告。 这是发送此信息时的回调代码。

import 'package:flutter/material.dart';
import 'package:todoey/models/Task.dart';
import 'package:todoey/screens/add_task_screen.dart';
import 'package:todoey/screens/bottom_section.dart';
import 'package:todoey/screens/top_section.dart';

class TasksScreen extends StatefulWidget {
  @override
  State<TasksScreen> createState() => _TasksScreenState();
}

class _TasksScreenState extends State<TasksScreen> {
  List<Task> tasks = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showModalBottomSheet(
            context: context,
            builder: (context) => SingleChildScrollView(
              child: Container(
                padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).viewInsets.bottom),
                child: AddTaskScreen(
                  callBack: (String taskTitle) {
                    setState(() {
                      print(taskTitle);
                      tasks.add(
                        Task(
                          name: taskTitle,
                        ),
                      );
                    });
                    Navigator.pop(context);
                  },
                ).build(context),
              ),
            ),
          );
        },
        child: Icon(
          Icons.add,
          color: Colors.white,
          size: 35,
        ),
        elevation: 5,
        backgroundColor: Colors.lightBlueAccent,
      ),
      backgroundColor: Colors.lightBlueAccent,
      body: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            TopSection(),
            SizedBox(
              height: 30,
            ),
            BottomSection(tasks: tasks),
          ],
        ),
      ),
    );
  }
}

对于主要 class,这是代码。

import 'package:flutter/material.dart';
import 'package:todoey/screens/task_screen.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: TasksScreen(),
    );
  }
}

在 flutter 中,您想将可变对象(例如您的 title)存储在 State 中。这是因为构建函数理论上可以多次调用,你无法控制它。因此,将变量存储在对象的 State 中可以让您在多次调用 build 时保持它“活着”。

这是您的示例,已按预期工作:

import 'package:flutter/material.dart';

class AddTaskScreen extends StatefulWidget {
  final Function callBack; // function

  AddTaskScreen({required this.callBack});

  @override
  State<AddTaskScreen> createState() => _AddTaskScreenState();
}

class _AddTaskScreenState extends State<AddTaskScreen> {
  /// Declare title in the state, so that its a long lived object
  var title = ""; // Initialize it (likely as empty)
  
  @override
  Widget build(BuildContext context) {

    return Container(
      height: 350,
      color: Color(0xff757575),
      child: Container(
        padding: EdgeInsets.all(20),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(20),
            topLeft: Radius.circular(20),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Text(
              'Add Task',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.lightBlueAccent,
                fontSize: 24,
              ),
            ),
            SizedBox(
              height: 20,
            ),
            TextField(
              textAlign: TextAlign.center,
              autofocus: false,
              style: TextStyle(
                color: Colors.black,
                fontSize: 15,
              ),
              onChanged: (value) {
                title = value; // taking the user input
              },
              decoration: InputDecoration(
                focusColor: Colors.lightBlueAccent,
                hintText: 'Type a Task',
                hintStyle: TextStyle(
                  color: Colors.grey,
                  fontSize: 12,
                ),
              ),
            ),
            SizedBox(
              height: 20,
            ),
            TextButton(
              onPressed: () {
                widget.callBack(title); // error
              },
              style: TextButton.styleFrom(
                backgroundColor: Colors.lightBlueAccent,
              ),
              child: Text(
                'Add',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

因此您使用的是无状态小部件,因此您的 onChanged 函数将不起作用,因为无状态小部件的状态不会更改以呈现 title[=14 的新值=],所以你可以把它改成一个有状态的小部件来查看效果。