How to present an empty view in flutter as Widget.build cannot return null to indicate that there is nothing to render.
The first way, assign the empty data with [] syntax. This creates an empty array list without elements. All the above are generic typed with dynamic values. The third way, If you want to create a typed empty number list, You have to assign with generic with int.
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 ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With