I tried this code but the tenary operator is not working as it should as I am getting error and if put String bgImage = (data['isDayTime']==null)? 'day.png' : 'night.png'; then I am only getting day.png I am getting this error
The following TypeErrorImpl was thrown building Home(dirty, dependencies: [_ModalScopeStatus], state: _HomeState#1a387): type 'Null' is not a 'bool' in boolean expression
Here is the code
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Map data = {};
@override
Widget build(BuildContext context) {
data=data.isNotEmpty ? data : ModalRoute.of(context)?.settings?.arguments as Map;
print(data);
String bgImage = data['isDayTime']? 'day.png' : 'night.png';
return Scaffold(
body: SafeArea(
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/$bgImage'),
fit: BoxFit.cover,
)
),
child: Padding(
padding: const EdgeInsets.fromLTRB(0,120.0,0,0),
child: Column(
children: <Widget>[
FlatButton.icon(
onPressed: () async {
dynamic result = await Navigator.pushNamed(context, '/location');
setState(() {
data ={
'time': result['time'],
'location': result['location'],
'isDaytime': result['isDaytime'],
'flag': result['flag'],
};
});
},
icon: Icon(
Icons.edit_location,
color: Colors.grey[300],
),
label: Text(
'Edit Location',
style: TextStyle(
color: Colors.grey[300],
),
),
),
SizedBox(height: 20.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
data['location'],
style: TextStyle(
fontSize: 28.0,
letterSpacing: 2.0
)
)
],
),
SizedBox(height: 20.0),
Text(
data['time'],
style: TextStyle(
fontSize: 66.0,
),
),
],
),
),
),
),
);
}
}
CodePudding user response:
Change your condition from data['isDayTime']?
to data['isDayTime']!=null && data['isDayTime']==true?
.
CodePudding user response:
The main issue is here you are passing bool? isDaytime
and this is nullable means it can be null. But
using String bgImage = data['isDayTime']? 'day.png' : 'night.png';
means here data['isDayTime']
either will be true or false. That's why you need to make sure you are not getting null value. Also, another null value can occur from modal route arguments.
1stly check if data['isDayTime']
is null or not, then check it. You can follow @Monik's answer.