How to present an empty view in flutter?
How to present an empty view in flutter as Widget.build cannot return null to indicate that there is nothing to render.
For anyone like me who was wondering what is "the correct way" to show an empty widget - official Material codebase uses this:
Widget build(BuildContext context) {
return SizedBox.shrink();
}
SizedBox.shrink()
is a widget that is unlike Container
or Material
has no background or any decorations whatsoever. It sizes itself to the smallest area possible, if not influenced by parent constraints.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
);
}
}
You can also simply return an empty Container
and avoid using the Scaffold
entirely. But this would result in a black screen if this is the only primary widget in you app, you can set the color
property of the Container
if you want to prevent the black background.
Example:
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white // This is optional
);
}
}