When we are building cross platform apps we generally want to have the same behaviour across all of the different platforms we target. With Flutter we currently can target Android, iOS and Web, with desktop support at the time of writing currently in beta.
However, sometimes, for whatever reason, we might need to implement different behaviours depending on the platform. It can be that we wish to display a different UI element depending on the platform or there might be a technical limitation.
So how can we check whether or not our Flutter app is compiled for the web?
We import and use:
import 'package:flutter/foundation.dart' show kIsWeb;
And then in our code we use ‘kIsWeb’ as boolean conditional, in our example we are just changing the text to display different values and change the background colour.
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
height: double.infinity,
width: double.infinity,
color: kIsWeb ? Colors.lightBlueAccent : Colors.greenAccent,
child: const Center(
child: Text(
kIsWeb ? "Is running on the web" : "Is running on other platforms",
),
)
),
);
}
For the full code example visit: https://github.com/Drysen1/flutter_quicktricks_kisweb
Leave a Reply