【发布时间】:2021-08-16 18:40:39
【问题描述】:
我对“可空表达式”有疑问。问题出在这两行:left: isSideBarOpenedAsync.data ? 0 : 0, 和right: isSideBarOpenedAsync.data ? 0 : screenWidth - 35, 我正在尝试用动画打开侧边栏菜单。一些想法来解决这个问题?泰。
这是错误:错误:'bool?' 类型的值不能分配给“bool”类型的变量,因为“bool?”可以为空,而 'bool' 不是。
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:solaris/constants.dart';
import 'package:rxdart/rxdart.dart';
class SideBar extends StatefulWidget {
@override
_SideBarState createState() => _SideBarState();
}
class _SideBarState extends State<SideBar> with SingleTickerProviderStateMixin<SideBar>{
late AnimationController _animationController;
late StreamController<bool> isSidebarOpenedStreamController;
late Stream<bool> isSideBarOpenedStream;
late StreamSink<bool> isSideBarOpenedSink;
final _animationDuration = const Duration(milliseconds: 500);
@override
void initState(){
super.initState();
_animationController = AnimationController(vsync: this, duration: _animationDuration);
isSidebarOpenedStreamController = PublishSubject<bool>();
isSideBarOpenedStream = isSidebarOpenedStreamController.stream;
isSideBarOpenedSink = isSidebarOpenedStreamController.sink;
}
@override
void dispose(){
_animationController.dispose();
isSidebarOpenedStreamController.close();
isSideBarOpenedSink.close();
super.dispose();
}
void onIconPressed(){
final animationStatus = _animationController.status;
final isAnimationCompleted = animationStatus == AnimationStatus.completed;
if(isAnimationCompleted){
isSideBarOpenedSink.add(false);
_animationController.reverse();
}else{
isSideBarOpenedSink.add(true);
_animationController.forward();
}
}
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return StreamBuilder<bool>(
initialData: false,
stream: isSideBarOpenedStream,
builder: (context, isSideBarOpenedAsync){
return AnimatedPositioned(
duration: _animationDuration,
top: 0,
bottom: 0,
left: isSideBarOpenedAsync.data ? 0 : 0,
right: isSideBarOpenedAsync.data ? 0 : screenWidth - 35,
child: Row(
children: <Widget>[
Expanded(
child: Container(
color: red,
),
),
Align(
alignment: Alignment(0,-0.9),
child: GestureDetector(
onTap: (){
onIconPressed();
},
child: Container(
width: 35,
height: 110,
color: blue,
alignment: Alignment.centerLeft,
child: AnimatedIcon(
progress: _animationController.view,
icon: AnimatedIcons.menu_close,
color: white,
size: 25,
),
),
),
),
],
),
);
},
);
}
}
【问题讨论】:
标签: flutter dart flutter-animation