首页 > 解决方案 > 必须先分配不可为空的局部变量“title”,然后才能使用它。颤振错误

问题描述

我想从变量中获取用户输入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变量。String当我传入这个函数时它有参数title它给了我一个警告。这是何时发送此信息的回调代码。

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),
          ],
        ),
      ),
    );
  }
}

对于主类,这里是代码。

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(),
    );
  }
}

标签: flutterdartstate-managementnon-nullable

解决方案


在颤振中,您希望将可变对象(例如 your title)存储在State. 这是因为 build 函数理论上可以多次调用,你无法控制它。因此,将变量存储在对象中可以让您在多次调用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,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

推荐阅读