Я использую AlertDialog и хочу включить или отключить в зависимости от условия. Тем не менее, я получаю эту ошибку подчеркивания, говорящую
The named parameter 'enabled' isn't defined. Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'enabled'.
actions: <Widget>[
TextButton(
enabled: false,
child: Text('Approve'),
onPressed: () async {
print('hello');
},
),
],
Как я могу заставить это работать?





Вкратце: enabled — это динамический геттер, который возвращает true, если onPressed или onLongPress установлены ненулевые значения, и возвращает false в противном случае.
Ответ можно найти, исследуя ButtonStyleButton, то есть Class, которое TextButton расширяет, а именно:
/// Whether the button is enabled or disabled.
///
/// Buttons are disabled by default. To enable a button, set its [onPressed]
/// or [onLongPress] properties to a non-null value.
bool get enabled => onPressed != null || onLongPress != null;
TextButton будет enabled, если у него есть обратный вызов onLongPress или onPressed, установленный на ненулевое значение.
Тем не менее, согласно указанному вами сценарию, мы могли бы построить TextButton следующим образом:
bool _enabled = true;
Widget _buildTextButton() {
return TextButton(
child: Text('Approve'),
onPressed: _enabled ? _onPressed() : null,
);
)
void _toggleEnabled() {
setState(() => _enabled = != _enabled);
}
void _onPressed() {
print('pressed!');
}
Вы можете скопировать и вставить полный код ниже
Шаг 1: Вы можете использовать обёртку StatefulBuilder AlertDialog
Шаг 2: позвоните setState(() => enable = true); и сообщите о своем состоянии
Шаг 3: В наборе onPressed
onPressed: enable
? () {
Navigator.of(context).pop();
}
: null),
фрагмент кода
Future<void> _showMyDialog(bool enable) async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return AlertDialog(
title: Text('AlertDialog Title'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('This is a demo alert dialog.'),
Text('Would you like to approve of this message?'),
TextButton(
child: Text("enable Approve"),
onPressed: () {
setState(() => enable = true);
},
),
],
),
),
actions: <Widget>[
TextButton(
child: Text('Approve'),
onPressed: enable
? () {
Navigator.of(context).pop();
}
: null),
],
);
});
});
}
рабочая демонстрация
полный код
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<void> _showMyDialog(bool enable) async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return AlertDialog(
title: Text('AlertDialog Title'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('This is a demo alert dialog.'),
Text('Would you like to approve of this message?'),
TextButton(
child: Text("enable Approve"),
onPressed: () {
setState(() => enable = true);
},
),
],
),
),
actions: <Widget>[
TextButton(
child: Text('Approve'),
onPressed: enable
? () {
Navigator.of(context).pop();
}
: null),
],
);
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
_showMyDialog(false);
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
О, так я думал, что это часть прямого свойства TextButton. Большое спасибо!