Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Luckey-Elijah/2893c2404e4cc9b66383f133db766c0a to your computer and use it in GitHub Desktop.
Save Luckey-Elijah/2893c2404e4cc9b66383f133db766c0a to your computer and use it in GitHub Desktop.
A simple example of using the spread (`...`) operator within a list of widgets conditionally.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(shouldBuildList: false),
);
}
}
class HomePage extends StatelessWidget {
final bool shouldBuildList;
const HomePage({Key key, @required this.shouldBuildList})
: assert(shouldBuildList != null),
super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(children: [
// This is where the list is conditionally injected.
if (shouldBuildList) ...[
MyCustomCard(data: 'This'),
MyCustomCard(data: 'is'),
],
MyCustomCard(data: 'my'),
MyCustomCard(data: 'list.'),
]),
),
);
}
}
class MyCustomCard extends StatelessWidget {
final String data;
const MyCustomCard({@required this.data}) : assert(data != null);
@override
Widget build(BuildContext context) {
return Card(child: Text(data));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment