#flutter #dart #dialog
#flutter #dart #диалог
Вопрос:
Я создал анимацию цветовой анимации, чтобы изменить цвет фона диалогового окна, но он по-прежнему не меняется.
Мой код:
void _showDialog() {
AnimationController? animationController = AnimationController(
vsync: this,
duration: const Duration(
milliseconds: 1000,
)
);
Animation<Color?>? animation = ColorTween(
begin: Colors.black54,
end: Colors.redAccent,
).animate(animationController!.view);
showDialog(
context: context,
builder: (BuildContext context) {
return Dialog(
backgroundColor: animation!.value,
elevation: 6,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)
),
child: MyTextWidget(
onSubmitted: (text) {
animationController.forward();
}
);
}
).then((value) => {
print(value)
});
}
Затем я использую AnimationController.forward(), но ничего не происходит.
Что я делаю не так?
Комментарии:
1. Я не могу сказать наверняка, но вы должны попробовать переместить весь диалог с помощью логики анимации в отдельный класс виджетов (чтобы функция ShowDialog возвращала новый виджет). Причина в том, что когда вы вызываете show dialog, он отображается в другом контексте, а также его маршрут основан на корневом навигаторе (т. Е. MaterialApp), поэтому его родительский элемент не совпадает с тем, где он был вызван, и, возможно, значения не обновляются должным образом… опять же, я не уверен на 100%, но навигация и диалог всегда доставляют неудобства по причинам, которые я упомянул.
2. Где вы вызываете AnimationController.forward() ?
3. @bluenile дочерний элемент: MyTextWidget( onSubmitted: (текст) { AnimationController.forward(); } )
Ответ №1:
Анимации не было, потому что вы не обернули свой диалог каким-либо виджетом, который бы анимировал. Пожалуйста, смотрите Рабочий код ниже единственное, что я сделал, это обернуть диалог с помощью AnimatedBuider и вызвать AnimationController.repeat() . Вы можете вызвать AnimationController.forward из своего пользовательского текстового виджета :
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
//theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidgets(),
),
),
);
}
}
class MyWidgets extends StatefulWidget {
@override
_MyWidgetsState createState() => _MyWidgetsState();
}
class _MyWidgetsState extends State<MyWidgets> with TickerProviderStateMixin {
void _showDialog() {
AnimationController animationController = AnimationController(
vsync: this,
duration: const Duration(
milliseconds: 1000,
));
Animation<Color> animation = ColorTween(
begin: Colors.black54,
end: Colors.redAccent,
).animate(animationController.view);
showDialog(
context: context,
builder: (BuildContext context) {
animationController.repeat();
return AnimatedBuilder(
animation: animation,
builder: (context, snapshot) {
return Dialog(
backgroundColor: animation.value,
elevation: 6,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)),
child: Container());
});
}).then((value) => {print(value)});
}
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: () {
_showDialog();
//animationController
},
child: const Text("Show Dialog"),
);
}
}