我目前正在测试并尝试 Flutter 应用程序的新设置页面。我是 Flutter 新手,所以我一直在学习教程,但是我收到了一个错误,该错误是教程视频中没有通过 VS Code 实现的,其中显示:
The named parameter 'username' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'username'.dartundefined_named_parameter
和
The parameter 'username' can't have a value of 'null' because of its type, but the implicit default value is 'null'. Try adding either an explicit non-'null' default value or the 'required' modifier.dartmissing_default_value_for_parameter
哪个 VS Code 在两个文件中都用红色下划线了“用户名”变量(分别为第 217 行和第 8 行)。我正在使用变量进行测试并在线查找解决方案,但我找不到我理解的非常简单的解决方案。如果这是一个非常简单的问题,我很抱歉,但我是 Flutter 新手,不明白出了什么问题。感谢您抽出时间。
代码的总体目标是保存用户名并将其显示在其他页面中。
main.dart 文件(第 148 - 222 行)
// Settings Page & Account Information
class Settings extends StatelessWidget {
Settings({Key? key}) : super(key: key);
final _usernameController = TextEditingController();
@override
Widget build(BuildContext context) {
final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
? 'DarkTheme'
: 'LightTheme';
return Scaffold(
appBar: AppBar(title: const Text('Settings'), actions: <Widget>[
IconButton(
onPressed: () async {
_saveSettings;
},
icon: const Icon(Icons.save),
tooltip: 'Save Settings')
]),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
child: Column(
children: [
Column(
// Account
children: [
const Padding(
padding: EdgeInsets.fromLTRB(0, 12, 0, 0),
child: Text('Account Information',
style: TextStyle(
fontSize: 17.0,
))),
Padding(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
child: TextField(
controller: _usernameController,
inputFormatters: [LengthLimitingTextInputFormatter(25)],
decoration: InputDecoration(
hintText: 'Username',
labelText: 'Username',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10.0)),
),
),
),
],
),
Container(
child: Column(
// App Settings
children: [
// SwitchListTile(value: DarkMode, onChanged: Light => Dark => Light)
// ChangeThemeButtonWidget(),
TextButton(
onPressed: _saveSettings,
child: const Text('Save Settings'))
],
),
),
],
),
)));
}
void _saveSettings() {
final newSettings = Settings(
username: _usernameController.text,
);
print(newSettings);
}
}
saved_data.dart 文件
import 'package:shared_preferences/shared_preferences.dart';
import 'package:bit/main.dart';
class Settings {
final String username;
Settings({
this.username,
});
}
最佳答案
您应该考虑为这两个类使用不同的名称。另外,对于第二个设置类,消息很明确:
Try adding either an explicit non-'null' default value or the 'required' modifier.dartmissing_default_value_for_parameter
所以,设置变成:
class SettingsModel {
final String username;
SettingsModel({
required this.username,
});
}
并且,设置应该是:
void _saveSettings() {
final newSettings = SettingsModel(
username: _usernameController.text,
);
}
关于flutter - 为共享首选项用户名定义变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71213385/